<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>

<meta charset="utf-8">
<meta name="generator" content="quarto-1.7.33">

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">


<title>1&nbsp; Introducing Zig – Introduction to Zig</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
  width: 0.8em;
  margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */ 
  vertical-align: middle;
}
/* CSS for syntax highlighting */
html { -webkit-text-size-adjust: 100%; }
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
  { counter-reset: source-line 0; }
pre.numberSource code > span
  { position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
  { content: counter(source-line);
    position: relative; left: -1em; text-align: right; vertical-align: baseline;
    border: none; display: inline-block;
    -webkit-touch-callout: none; -webkit-user-select: none;
    -khtml-user-select: none; -moz-user-select: none;
    -ms-user-select: none; user-select: none;
    padding: 0 4px; width: 4em;
  }
pre.numberSource { margin-left: 3em;  padding-left: 4px; }
div.sourceCode
  {   }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
/* CSS for citations */
div.csl-bib-body { }
div.csl-entry {
  clear: both;
  margin-bottom: 0em;
}
.hanging-indent div.csl-entry {
  margin-left:2em;
  text-indent:-2em;
}
div.csl-left-margin {
  min-width:2em;
  float:left;
}
div.csl-right-inline {
  margin-left:2em;
  padding-left:1em;
}
div.csl-indent {
  margin-left: 2em;
}</style>


<script src="../site_libs/quarto-nav/quarto-nav.js"></script>
<script src="../site_libs/quarto-nav/headroom.min.js"></script>
<script src="../site_libs/clipboard/clipboard.min.js"></script>
<script src="../site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="../site_libs/quarto-search/fuse.min.js"></script>
<script src="../site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="../">
<link href="../Chapters/03-structs.html" rel="next">
<link href="../index.html" rel="prev">
<script src="../site_libs/quarto-html/quarto.js" type="module"></script>
<script src="../site_libs/quarto-html/tabsets/tabsets.js" type="module"></script>
<script src="../site_libs/quarto-html/popper.min.js"></script>
<script src="../site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="../site_libs/quarto-html/anchor.min.js"></script>
<link href="../site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-59898bd1c6b9d2bb783127feaa000c76.css" rel="stylesheet" class="quarto-color-scheme" id="quarto-text-highlighting-styles">
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-dark-d329e753491efaeac79c98c4b193a686.css" rel="stylesheet" class="quarto-color-scheme quarto-color-alternate" id="quarto-text-highlighting-styles">
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-59898bd1c6b9d2bb783127feaa000c76.css" rel="stylesheet" class="quarto-color-scheme-extra" id="quarto-text-highlighting-styles">
<script src="../site_libs/bootstrap/bootstrap.min.js"></script>
<link href="../site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="../site_libs/bootstrap/bootstrap-5a7d69291c2a8c67bc3a157f4354e263.min.css" rel="stylesheet" append-hash="true" class="quarto-color-scheme" id="quarto-bootstrap" data-mode="light">
<link href="../site_libs/bootstrap/bootstrap-dark-a459d9a911ec262923466a12d18bc01e.min.css" rel="stylesheet" append-hash="true" class="quarto-color-scheme quarto-color-alternate" id="quarto-bootstrap" data-mode="dark">
<link href="../site_libs/bootstrap/bootstrap-5a7d69291c2a8c67bc3a157f4354e263.min.css" rel="stylesheet" append-hash="true" class="quarto-color-scheme-extra" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
  "location": "sidebar",
  "copy-button": false,
  "collapse-after": 3,
  "panel-placement": "start",
  "type": "textbox",
  "limit": 50,
  "keyboard-shortcut": [
    "f",
    "/",
    "s"
  ],
  "show-item-context": false,
  "language": {
    "search-no-results-text": "No results",
    "search-matching-documents-text": "matching documents",
    "search-copy-link-title": "Copy link to search",
    "search-hide-matches-text": "Hide additional matches",
    "search-more-match-text": "more match in this document",
    "search-more-matches-text": "more matches in this document",
    "search-clear-button-title": "Clear",
    "search-text-placeholder": "",
    "search-detached-cancel-button-title": "Cancel",
    "search-submit-button-title": "Submit",
    "search-label": "Search"
  }
}</script>
<script async="" src="https://www.googletagmanager.com/gtag/js?id=G-6CHJXK4CEV"></script>

<script type="text/javascript">

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-6CHJXK4CEV', { 'anonymize_ip': true});
</script>


</head>

<body class="nav-sidebar floating quarto-light"><script id="quarto-html-before-body" type="application/javascript">
    const toggleBodyColorMode = (bsSheetEl) => {
      const mode = bsSheetEl.getAttribute("data-mode");
      const bodyEl = window.document.querySelector("body");
      if (mode === "dark") {
        bodyEl.classList.add("quarto-dark");
        bodyEl.classList.remove("quarto-light");
      } else {
        bodyEl.classList.add("quarto-light");
        bodyEl.classList.remove("quarto-dark");
      }
    }
    const toggleBodyColorPrimary = () => {
      const bsSheetEl = window.document.querySelector("link#quarto-bootstrap:not([rel=disabled-stylesheet])");
      if (bsSheetEl) {
        toggleBodyColorMode(bsSheetEl);
      }
    }
    const setColorSchemeToggle = (alternate) => {
      const toggles = window.document.querySelectorAll('.quarto-color-scheme-toggle');
      for (let i=0; i < toggles.length; i++) {
        const toggle = toggles[i];
        if (toggle) {
          if (alternate) {
            toggle.classList.add("alternate");
          } else {
            toggle.classList.remove("alternate");
          }
        }
      }
    };
    const toggleColorMode = (alternate) => {
      // Switch the stylesheets
      const primaryStylesheets = window.document.querySelectorAll('link.quarto-color-scheme:not(.quarto-color-alternate)');
      const alternateStylesheets = window.document.querySelectorAll('link.quarto-color-scheme.quarto-color-alternate');
      manageTransitions('#quarto-margin-sidebar .nav-link', false);
      if (alternate) {
        // note: dark is layered on light, we don't disable primary!
        enableStylesheet(alternateStylesheets);
        for (const sheetNode of alternateStylesheets) {
          if (sheetNode.id === "quarto-bootstrap") {
            toggleBodyColorMode(sheetNode);
          }
        }
      } else {
        disableStylesheet(alternateStylesheets);
        enableStylesheet(primaryStylesheets)
        toggleBodyColorPrimary();
      }
      manageTransitions('#quarto-margin-sidebar .nav-link', true);
      // Switch the toggles
      setColorSchemeToggle(alternate)
      // Hack to workaround the fact that safari doesn't
      // properly recolor the scrollbar when toggling (#1455)
      if (navigator.userAgent.indexOf('Safari') > 0 && navigator.userAgent.indexOf('Chrome') == -1) {
        manageTransitions("body", false);
        window.scrollTo(0, 1);
        setTimeout(() => {
          window.scrollTo(0, 0);
          manageTransitions("body", true);
        }, 40);
      }
    }
    const disableStylesheet = (stylesheets) => {
      for (let i=0; i < stylesheets.length; i++) {
        const stylesheet = stylesheets[i];
        stylesheet.rel = 'disabled-stylesheet';
      }
    }
    const enableStylesheet = (stylesheets) => {
      for (let i=0; i < stylesheets.length; i++) {
        const stylesheet = stylesheets[i];
        if(stylesheet.rel !== 'stylesheet') { // for Chrome, which will still FOUC without this check
          stylesheet.rel = 'stylesheet';
        }
      }
    }
    const manageTransitions = (selector, allowTransitions) => {
      const els = window.document.querySelectorAll(selector);
      for (let i=0; i < els.length; i++) {
        const el = els[i];
        if (allowTransitions) {
          el.classList.remove('notransition');
        } else {
          el.classList.add('notransition');
        }
      }
    }
    const isFileUrl = () => {
      return window.location.protocol === 'file:';
    }
    const hasAlternateSentinel = () => {
      let styleSentinel = getColorSchemeSentinel();
      if (styleSentinel !== null) {
        return styleSentinel === "alternate";
      } else {
        return false;
      }
    }
    const setStyleSentinel = (alternate) => {
      const value = alternate ? "alternate" : "default";
      if (!isFileUrl()) {
        window.localStorage.setItem("quarto-color-scheme", value);
      } else {
        localAlternateSentinel = value;
      }
    }
    const getColorSchemeSentinel = () => {
      if (!isFileUrl()) {
        const storageValue = window.localStorage.getItem("quarto-color-scheme");
        return storageValue != null ? storageValue : localAlternateSentinel;
      } else {
        return localAlternateSentinel;
      }
    }
    const toggleGiscusIfUsed = (isAlternate, darkModeDefault) => {
      const baseTheme = document.querySelector('#giscus-base-theme')?.value ?? 'light';
      const alternateTheme = document.querySelector('#giscus-alt-theme')?.value ?? 'dark';
      let newTheme = '';
      if(authorPrefersDark) {
        newTheme = isAlternate ? baseTheme : alternateTheme;
      } else {
        newTheme = isAlternate ? alternateTheme : baseTheme;
      }
      const changeGiscusTheme = () => {
        // From: https://github.com/giscus/giscus/issues/336
        const sendMessage = (message) => {
          const iframe = document.querySelector('iframe.giscus-frame');
          if (!iframe) return;
          iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app');
        }
        sendMessage({
          setConfig: {
            theme: newTheme
          }
        });
      }
      const isGiscussLoaded = window.document.querySelector('iframe.giscus-frame') !== null;
      if (isGiscussLoaded) {
        changeGiscusTheme();
      }
    };
    const authorPrefersDark = false;
    const darkModeDefault = authorPrefersDark;
      document.querySelector('link#quarto-text-highlighting-styles.quarto-color-scheme-extra').rel = 'disabled-stylesheet';
      document.querySelector('link#quarto-bootstrap.quarto-color-scheme-extra').rel = 'disabled-stylesheet';
    let localAlternateSentinel = darkModeDefault ? 'alternate' : 'default';
    // Dark / light mode switch
    window.quartoToggleColorScheme = () => {
      // Read the current dark / light value
      let toAlternate = !hasAlternateSentinel();
      toggleColorMode(toAlternate);
      setStyleSentinel(toAlternate);
      toggleGiscusIfUsed(toAlternate, darkModeDefault);
      window.dispatchEvent(new Event('resize'));
    };
    // Switch to dark mode if need be
    if (hasAlternateSentinel()) {
      toggleColorMode(true);
    } else {
      toggleColorMode(false);
    }
  </script>

<div id="quarto-search-results"></div>
  <header id="quarto-header" class="headroom fixed-top">
  <nav class="quarto-secondary-nav">
    <div class="container-fluid d-flex">
      <button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" role="button" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
        <i class="bi bi-layout-text-sidebar-reverse"></i>
      </button>
        <nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="../Chapters/01-zig-weird.html"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Introducing Zig</span></a></li></ol></nav>
        <a class="flex-grow-1" role="navigation" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">      
        </a>
      <button type="button" class="btn quarto-search-button" aria-label="Search" onclick="window.quartoOpenSearch();">
        <i class="bi bi-search"></i>
      </button>
    </div>
  </nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
  <nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation floating overflow-auto">
    <div class="pt-lg-2 mt-2 text-left sidebar-header">
    <div class="sidebar-title mb-0 py-0">
      <a href="../">Introduction to Zig</a> 
        <div class="sidebar-tools-main">
  <a href="" class="quarto-color-scheme-toggle quarto-navigation-tool  px-1" onclick="window.quartoToggleColorScheme(); return false;" title="Toggle dark mode"><i class="bi"></i></a>
</div>
    </div>
      </div>
        <div class="mt-2 flex-shrink-0 align-items-center">
        <div class="sidebar-search">
        <div id="quarto-search" class="" title="Search"></div>
        </div>
        </div>
    <div class="sidebar-menu-container"> 
    <ul class="list-unstyled mt-1">
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../index.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text">Welcome</span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/01-zig-weird.html" class="sidebar-item-text sidebar-link active">
 <span class="menu-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Introducing Zig</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/03-structs.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Control flow, structs, modules and types</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/01-memory.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Memory and Allocators</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/01-base64.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">4</span>&nbsp; <span class="chapter-title">Project 1 - Building a base64 encoder/decoder</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/02-debugging.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">5</span>&nbsp; <span class="chapter-title">Debugging Zig applications</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/05-pointers.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">6</span>&nbsp; <span class="chapter-title">Pointers and Optionals</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/04-http-server.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">7</span>&nbsp; <span class="chapter-title">Project 2 - Building a HTTP Server from scratch</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/03-unittests.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">8</span>&nbsp; <span class="chapter-title">Unit tests</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/07-build-system.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">9</span>&nbsp; <span class="chapter-title">Build System</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/09-error-handling.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">10</span>&nbsp; <span class="chapter-title">Error handling and unions</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/09-data-structures.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">11</span>&nbsp; <span class="chapter-title">Data Structures</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/10-stack-project.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">12</span>&nbsp; <span class="chapter-title">Project 3 - Building a stack data structure</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/12-file-op.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">13</span>&nbsp; <span class="chapter-title">Filesystem and Input/Output (IO)</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/14-zig-c-interop.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">14</span>&nbsp; <span class="chapter-title">Zig interoperability with C</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/13-image-filter.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">15</span>&nbsp; <span class="chapter-title">Project 4 - Developing an image filter</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/14-threads.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">16</span>&nbsp; <span class="chapter-title">Introducing threads and parallelism in Zig</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/15-vectors.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text"><span class="chapter-number">17</span>&nbsp; <span class="chapter-title">Introducing Vectors and SIMD</span></span></a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="../Chapters/references.html" class="sidebar-item-text sidebar-link">
 <span class="menu-text">References</span></a>
  </div>
</li>
    </ul>
    </div>
</nav>
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div>
<!-- margin-sidebar -->
    <div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
        <nav id="TOC" role="doc-toc" class="toc-active">
    <h2 id="toc-title">Table of contents</h2>
   
  <ul>
  <li><a href="#what-is-zig" id="toc-what-is-zig" class="nav-link active" data-scroll-target="#what-is-zig"><span class="header-section-number">1.1</span> What is Zig?</a></li>
  <li><a href="#hello-world-in-zig" id="toc-hello-world-in-zig" class="nav-link" data-scroll-target="#hello-world-in-zig"><span class="header-section-number">1.2</span> Hello world in Zig</a>
  <ul class="collapse">
  <li><a href="#sec-project-files" id="toc-sec-project-files" class="nav-link" data-scroll-target="#sec-project-files"><span class="header-section-number">1.2.1</span> Understanding the project files</a></li>
  <li><a href="#sec-root-file" id="toc-sec-root-file" class="nav-link" data-scroll-target="#sec-root-file"><span class="header-section-number">1.2.2</span> The file <code>root.zig</code></a></li>
  <li><a href="#sec-main-file" id="toc-sec-main-file" class="nav-link" data-scroll-target="#sec-main-file"><span class="header-section-number">1.2.3</span> The <code>main.zig</code> file</a></li>
  <li><a href="#sec-compile-code" id="toc-sec-compile-code" class="nav-link" data-scroll-target="#sec-compile-code"><span class="header-section-number">1.2.4</span> Compiling your source code</a></li>
  <li><a href="#sec-compile-run-code" id="toc-sec-compile-run-code" class="nav-link" data-scroll-target="#sec-compile-run-code"><span class="header-section-number">1.2.5</span> Compile and execute at the same time</a></li>
  <li><a href="#important-note-for-windows-users" id="toc-important-note-for-windows-users" class="nav-link" data-scroll-target="#important-note-for-windows-users"><span class="header-section-number">1.2.6</span> Important note for Windows users</a></li>
  <li><a href="#sec-compile-project" id="toc-sec-compile-project" class="nav-link" data-scroll-target="#sec-compile-project"><span class="header-section-number">1.2.7</span> Compiling the entire project</a></li>
  </ul></li>
  <li><a href="#how-to-learn-zig" id="toc-how-to-learn-zig" class="nav-link" data-scroll-target="#how-to-learn-zig"><span class="header-section-number">1.3</span> How to learn Zig?</a></li>
  <li><a href="#sec-assignments" id="toc-sec-assignments" class="nav-link" data-scroll-target="#sec-assignments"><span class="header-section-number">1.4</span> Creating new objects in Zig (i.e., identifiers)</a>
  <ul class="collapse">
  <li><a href="#constant-objects-vs-variable-objects" id="toc-constant-objects-vs-variable-objects" class="nav-link" data-scroll-target="#constant-objects-vs-variable-objects"><span class="header-section-number">1.4.1</span> Constant objects vs variable objects</a></li>
  <li><a href="#declaring-without-an-initial-value" id="toc-declaring-without-an-initial-value" class="nav-link" data-scroll-target="#declaring-without-an-initial-value"><span class="header-section-number">1.4.2</span> Declaring without an initial value</a></li>
  <li><a href="#there-is-no-such-thing-as-unused-objects" id="toc-there-is-no-such-thing-as-unused-objects" class="nav-link" data-scroll-target="#there-is-no-such-thing-as-unused-objects"><span class="header-section-number">1.4.3</span> There is no such thing as unused objects</a></li>
  <li><a href="#you-must-mutate-every-variable-objects" id="toc-you-must-mutate-every-variable-objects" class="nav-link" data-scroll-target="#you-must-mutate-every-variable-objects"><span class="header-section-number">1.4.4</span> You must mutate every variable objects</a></li>
  </ul></li>
  <li><a href="#sec-primitive-data-types" id="toc-sec-primitive-data-types" class="nav-link" data-scroll-target="#sec-primitive-data-types"><span class="header-section-number">1.5</span> Primitive Data Types</a></li>
  <li><a href="#sec-arrays" id="toc-sec-arrays" class="nav-link" data-scroll-target="#sec-arrays"><span class="header-section-number">1.6</span> Arrays</a>
  <ul class="collapse">
  <li><a href="#sec-select-array-elem" id="toc-sec-select-array-elem" class="nav-link" data-scroll-target="#sec-select-array-elem"><span class="header-section-number">1.6.1</span> Selecting elements of the array</a></li>
  <li><a href="#more-on-slices" id="toc-more-on-slices" class="nav-link" data-scroll-target="#more-on-slices"><span class="header-section-number">1.6.2</span> More on slices</a></li>
  <li><a href="#array-operators" id="toc-array-operators" class="nav-link" data-scroll-target="#array-operators"><span class="header-section-number">1.6.3</span> Array operators</a></li>
  <li><a href="#runtime-versus-compile-time-known-length-in-slices" id="toc-runtime-versus-compile-time-known-length-in-slices" class="nav-link" data-scroll-target="#runtime-versus-compile-time-known-length-in-slices"><span class="header-section-number">1.6.4</span> Runtime versus compile-time known length in slices</a></li>
  </ul></li>
  <li><a href="#sec-blocks" id="toc-sec-blocks" class="nav-link" data-scroll-target="#sec-blocks"><span class="header-section-number">1.7</span> Blocks and scopes</a></li>
  <li><a href="#sec-zig-strings" id="toc-sec-zig-strings" class="nav-link" data-scroll-target="#sec-zig-strings"><span class="header-section-number">1.8</span> How strings work in Zig?</a>
  <ul class="collapse">
  <li><a href="#using-a-slice-versus-a-sentinel-terminated-array" id="toc-using-a-slice-versus-a-sentinel-terminated-array" class="nav-link" data-scroll-target="#using-a-slice-versus-a-sentinel-terminated-array"><span class="header-section-number">1.8.1</span> Using a slice versus a sentinel-terminated array</a></li>
  <li><a href="#iterating-through-the-string" id="toc-iterating-through-the-string" class="nav-link" data-scroll-target="#iterating-through-the-string"><span class="header-section-number">1.8.2</span> Iterating through the string</a></li>
  <li><a href="#a-better-look-at-the-object-type" id="toc-a-better-look-at-the-object-type" class="nav-link" data-scroll-target="#a-better-look-at-the-object-type"><span class="header-section-number">1.8.3</span> A better look at the object type</a></li>
  <li><a href="#byte-vs-unicode-points" id="toc-byte-vs-unicode-points" class="nav-link" data-scroll-target="#byte-vs-unicode-points"><span class="header-section-number">1.8.4</span> Byte vs unicode points</a></li>
  <li><a href="#sec-strings-useful-funs" id="toc-sec-strings-useful-funs" class="nav-link" data-scroll-target="#sec-strings-useful-funs"><span class="header-section-number">1.8.5</span> Some useful functions for strings</a></li>
  </ul></li>
  <li><a href="#safety-in-zig" id="toc-safety-in-zig" class="nav-link" data-scroll-target="#safety-in-zig"><span class="header-section-number">1.9</span> Safety in Zig</a></li>
  <li><a href="#other-parts-of-zig" id="toc-other-parts-of-zig" class="nav-link" data-scroll-target="#other-parts-of-zig"><span class="header-section-number">1.10</span> Other parts of Zig</a></li>
  </ul>
</nav>
    </div>
<!-- main -->
<main class="content" id="quarto-document-content">


<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Introducing Zig</span></h1>
</div>



<div class="quarto-title-meta">

    
  
    
  </div>
  


</header>


<p>In this chapter, I want to introduce you to the world of Zig. Zig is a very young language that is being actively developed. As a consequence, its world is still very wild and to be explored. This book is my attempt to help you on your personal journey for understanding and exploring the exciting world of Zig.</p>
<p>I assume you have previous experience with some programming language in this book, not necessarily with a low-level one. So, if you have experience with Python, or Javascript, for example, it will be fine. But, if you do have experience with low-level languages, such as C, C++, or Rust, you will probably learn faster throughout this book.</p>
<section id="what-is-zig" class="level2" data-number="1.1">
<h2 data-number="1.1" class="anchored" data-anchor-id="what-is-zig"><span class="header-section-number">1.1</span> What is Zig?</h2>
<p>Zig is a modern, low-level, and general-purpose programming language. Some programmers think of Zig as a modern and better version of C.</p>
<p>In the author’s personal interpretation, Zig is tightly connected with “less is more”. Instead of trying to become a modern language by adding more and more features, many of the core improvements that Zig brings to the table are actually about removing annoying behaviours/features from C and C++. In other words, Zig tries to be better by simplifying the language, and by having more consistent and robust behaviour. As a result, analyzing, writing and debugging applications become much easier and simpler in Zig, than it is in C or C++.</p>
<p>This philosophy becomes clear with the following phrase from the official website of Zig:</p>
<blockquote class="blockquote">
<p>“Focus on debugging your application rather than debugging your programming language knowledge”.</p>
</blockquote>
<p>This phrase is specially true for C++ programmers. Because C++ is a gigantic language, with tons of features, and also, there are lots of different “flavors of C++”. These elements are what makes C++ so complex and hard to learn. Zig tries to go in the opposite direction. Zig is a very simple language, more closely related to other simple languages such as C and Go.</p>
<p>The phrase above is still important for C programmers too. Because, even C being a simple language, it’s still hard sometimes to read and understand C code. For example, pre-processor macros in C are a frequent source of confusion. Sometimes, they really make it hard to debug C programs. Because macros are essentially a second language embedded in C that obscures your C code. With macros, you are no longer 100% sure about which pieces of the code are being sent to the compiler, i.e. they obscure the actual source code that you wrote.</p>
<p>You don’t have macros in Zig. In Zig, the code you write, is the actual code that gets compiled by the compiler. You also don’t have a hidden control flow happening behind the scenes. And, you also don’t have functions or operators from the standard library that make hidden memory allocations behind your back.</p>
<p>By being a simpler language, Zig becomes much more clear and easier to read/write, but at the same time, it also achieves a much more robust state, with more consistent behaviour in edge situations. Once again, less is more.</p>
</section>
<section id="hello-world-in-zig" class="level2" data-number="1.2">
<h2 data-number="1.2" class="anchored" data-anchor-id="hello-world-in-zig"><span class="header-section-number">1.2</span> Hello world in Zig</h2>
<p>We begin our journey in Zig by creating a small “Hello World” program. To start a new Zig project in your computer, you simply call the <code>init</code> command from the <code>zig</code> compiler. Just create a new directory in your computer, then, init a new Zig project inside this directory, like this:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">mkdir</span> hello_world</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="bu">cd</span> hello_world</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="ex">zig</span> init</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>info: created build.zig
info: created build.zig.zon
info: created src/main.zig
info: created src/root.zig
info: see `zig build --help` for a menu of options</code></pre>
<section id="sec-project-files" class="level3" data-number="1.2.1">
<h3 data-number="1.2.1" class="anchored" data-anchor-id="sec-project-files"><span class="header-section-number">1.2.1</span> Understanding the project files</h3>
<p>After you run the <code>init</code> command from the <code>zig</code> compiler, some new files are created inside of your current directory. First, a “source” (<code>src</code>) directory is created, containing two files, <code>main.zig</code> and <code>root.zig</code>. Each <code>.zig</code> file is a separate Zig module, which is simply a text file that contains some Zig code.</p>
<p>By convention, the <code>main.zig</code> module is where your main function lives. Thus, if you are building an executable program in Zig, you need to declare a <code>main()</code> function, which represents the entrypoint of your program, i.e., where the execution of your program begins.</p>
<p>However, if you are building a library (instead of an executable program), then, the normal procedure is to delete this <code>main.zig</code> file and start with the <code>root.zig</code> module. By convention, the <code>root.zig</code> module is the root source file of your library.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ex">tree</span> .</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>.
├── build.zig
├── build.zig.zon
└── src
    ├── main.zig
    └── root.zig

1 directory, 4 files</code></pre>
<p>The <code>init</code> command also creates two additional files in our working directory: <code>build.zig</code> and <code>build.zig.zon</code>. The first file (<code>build.zig</code>) represents a build script written in Zig. This script is executed when you call the <code>build</code> command from the <code>zig</code> compiler. In other words, this file contains Zig code that executes the necessary steps to build the entire project.</p>
<p>Low-level languages normally use a compiler to build your source code into binary executables or binary libraries. Nevertheless, this process of compiling your source code and building binary executables or binary libraries from it, became a real challenge in the programming world, once the projects became bigger and bigger. As a result, programmers created “build systems”, which are a second set of tools designed to make this process of compiling and building complex projects, easier.</p>
<p>Examples of build systems are CMake, GNU Make, GNU Autoconf and Ninja, which are used to build complex C and C++ projects. With these systems, you can write scripts, which are called “build scripts”. They simply are scripts that describes the necessary steps to compile/build your project.</p>
<p>However, these are separate tools, that do not belong to C/C++ compilers, like <code>gcc</code> or <code>clang</code>. As a result, in C/C++ projects, you have not only to install and manage your C/C++ compilers, but you also have to install and manage these build systems separately.</p>
<p>In Zig, we don’t need to use a separate set of tools to build our projects, because a build system is embedded inside the language itself. We can use this build system to write small scripts in Zig, which describe the necessary steps to build/compile our Zig project<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>. So, everything you need to build a complex Zig project is the <code>zig</code> compiler, and nothing more.</p>
<p>The second generated file (<code>build.zig.zon</code>) is a JSON-like file, in which you can describe your project, and also, declare a set of dependencies of your project that you want to fetch from the internet. In other words, you can use this <code>build.zig.zon</code> file to include a list of external libraries in your project.</p>
<p>One possible way to include an external Zig library in your project, is to manually build and install the library in your system, and just link your source code with the library at the build step of your project.</p>
<p>However, if this external Zig library is available on GitHub for example, and it has a valid <code>build.zig.zon</code> file in the root folder of the project, which describes the project, you can easily include this library in your project by simply listing this external library in your <code>build.zig.zon</code> file.</p>
<p>In other words, this <code>build.zig.zon</code> file works similarly to the <code>package.json</code> file in Javascript projects, or the <code>Pipfile</code> file in Python projects, or the <code>Cargo.toml</code> file in Rust projects. You can read more about this specific file in a couple of articles on the internet<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a><a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a>, and you can also see the expected schema for this <code>build.zig.zon</code> file in a documentation file inside the official repository of Zig<a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a>.</p>
</section>
<section id="sec-root-file" class="level3" data-number="1.2.2">
<h3 data-number="1.2.2" class="anchored" data-anchor-id="sec-root-file"><span class="header-section-number">1.2.2</span> The file <code>root.zig</code></h3>
<p>Let’s take a look into the <code>root.zig</code> file. You might have noticed that every line of code with an expression ends with a semicolon (<code>;</code>). This follows the syntax of a C-family programming language<a href="#fn5" class="footnote-ref" id="fnref5" role="doc-noteref"><sup>5</sup></a>.</p>
<p>Also, notice the <code>@import()</code> call at the first line. We use this built-in function to import functionality from other Zig modules into our current module. This <code>@import()</code> function works similarly to the <code>#include</code> pre-processor in C or C++, or, to the <code>import</code> statement in Python or Javascript code. In this example, we are importing the <code>std</code> module, which gives you access to the Zig Standard Library.</p>
<p>In this <code>root.zig</code> file, we can also see how assignments (i.e., creating new objects) are made in Zig. You can create a new object in Zig by using the syntax <code>(const|var) name = value;</code>. In the example below, we are creating two constant objects (<code>std</code> and <code>testing</code>). In <a href="#sec-assignments" class="quarto-xref"><span>Section 1.4</span></a> we talk more about objects in general.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb5"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> testing = std.testing;</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="kw">export</span> <span class="kw">fn</span> add(a: <span class="dt">i32</span>, b: <span class="dt">i32</span>) <span class="dt">i32</span> <span class="op">{</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">return</span> a + b;</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Functions in Zig are declared using the <code>fn</code> keyword. In this <code>root.zig</code> module, we are declaring a function called <code>add()</code>, which has two arguments named <code>a</code> and <code>b</code>. The function returns an integer of the type <code>i32</code> as result.</p>
<p>Zig is a strongly-typed language. There are some specific situations where you can (if you want to) omit the type of an object in your code, if this type can be inferred by the <code>zig</code> compiler (we talk more about that in <a href="03-structs.html#sec-type-inference" class="quarto-xref"><span>Section 2.4</span></a>). But there are other situations where you do need to be explicit. For example, you do have to explicitly specify the type of each function argument, and also, the return type of every function that you create in Zig.</p>
<p>We specify the type of an object or a function argument in Zig by using a colon character (<code>:</code>) followed by the type after the name of this object/function argument. With the expressions <code>a: i32</code> and <code>b: i32</code>, we know that both <code>a</code> and <code>b</code> arguments have type <code>i32</code>, which is a signed 32 bit integer. In this part, the syntax in Zig is identical to the syntax in Rust, which also specifies types by using the colon character.</p>
<p>Lastly, we have the return type of the function at the end of the line, before we open the curly braces to start writing the function’s body. In the example above, this type is also a signed 32 bit integer (<code>i32</code>) value.</p>
<p>Notice that we also have an <code>export</code> keyword before the function declaration. This keyword is similar to the <code>extern</code> keyword in C. It exposes the function to make it available in the library API. Therefore, if you are writing a library for other people to use, you have to expose the functions you write in the public API of this library by using this <code>export</code> keyword. If we removed the <code>export</code> keyword from the <code>add()</code> function declaration, then, this function would be no longer exposed in the library object built by the <code>zig</code> compiler.</p>
</section>
<section id="sec-main-file" class="level3" data-number="1.2.3">
<h3 data-number="1.2.3" class="anchored" data-anchor-id="sec-main-file"><span class="header-section-number">1.2.3</span> The <code>main.zig</code> file</h3>
<p>Now that we have learned a lot about Zig’s syntax from the <code>root.zig</code> file, let’s take a look at the <code>main.zig</code> file. A lot of the elements we saw in <code>root.zig</code> are also present in <code>main.zig</code>. But there are some other elements that we haven’t seen yet, so let’s dive in.</p>
<p>First, look at the return type of the <code>main()</code> function in this file. We can see a small change. The return type of the function (<code>void</code>) is accompanied by an exclamation mark (<code>!</code>). This exclamation mark tells us that this <code>main()</code> function might return an error.</p>
<p>It’s worth noting that, a <code>main()</code> function in Zig is allowed to return nothing (<code>void</code>), or an unsigned 8-bit integer (<code>u8</code>) value<a href="#fn6" class="footnote-ref" id="fnref6" role="doc-noteref"><sup>6</sup></a>, or an error. In other words, you can write your <code>main()</code> function in Zig to return essentially nothing (<code>void</code>), or, if you prefer, you can also write a more C-like <code>main()</code> function, which returns an integer value that usually serves as a “status code” for the process.</p>
<p>In this example, the return type annotation of <code>main()</code> indicates that this function can either return nothing (<code>void</code>), or return an error. This exclamation mark in the return type annotation is an interesting and powerful feature of Zig. In summary, if you write a function and something inside the body of this function might return an error, then, you are forced to:</p>
<ul>
<li>either add the exclamation mark to the return type of the function and make it clear that this function might return an error.</li>
<li>explicitly handle this error inside the function.</li>
</ul>
<p>In most programming languages, we normally handle (or deal with) an error through a <em>try catch</em> pattern. Zig does have both <code>try</code> and <code>catch</code> keywords. But they work a little differently than what you’re probably used to in other languages.</p>
<p>If we look at the <code>main()</code> function below, you can see that we do have a <code>try</code> keyword on the 5th line. But we do not have a <code>catch</code> keyword in this code. In Zig, we use the <code>try</code> keyword to execute an expression that might return an error, which, in this example, is the <code>stdout.print()</code> expression.</p>
<p>In essence, the <code>try</code> keyword executes the expression <code>stdout.print()</code>. If this expression returns a valid value, then, the <code>try</code> keyword does absolutely nothing. It only passes the value forward. It’s like if this <code>try</code> keyword was never there. However, if the expression does return an error, then, the <code>try</code> keyword will unwrap the error value, then, it returns this error from the function and also prints the current stack trace to <code>stderr</code>.</p>
<p>This might sound weird to you if you come from a high-level language. Because in high-level languages, such as Python, if an error occurs somewhere, this error is automatically returned and the execution of your program will automatically stop even if you don’t want to stop the execution. You are obligated to face the error.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"Hello, {s}!</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="st">"world"</span><span class="op">}</span>);</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Another thing that you might have noticed in this code example, is that the <code>main()</code> function is marked with the <code>pub</code> keyword. It marks the <code>main()</code> function as a <em>public function</em> from this module. Every function in your Zig module is by default private to this Zig module and can only be called from within the module. Unless, you explicitly mark this function as a public function with the <code>pub</code> keyword.</p>
<p>If you think about it, this <code>pub</code> keyword in Zig does essentially the opposite of what the <code>static</code> keyword do in C/C++. By making a function “public” you allow other Zig modules to access and call this function. A calling Zig module imports another module by using the <code>@import()</code> built-in function, which makes all public functions from the imported module visible to the calling Zig module.</p>
</section>
<section id="sec-compile-code" class="level3" data-number="1.2.4">
<h3 data-number="1.2.4" class="anchored" data-anchor-id="sec-compile-code"><span class="header-section-number">1.2.4</span> Compiling your source code</h3>
<p>You can compile your Zig modules into a binary executable by running the <code>build-exe</code> command from the <code>zig</code> compiler. You simply list all the Zig modules that you want to build after the <code>build-exe</code> command, separated by spaces. In the example below, we are compiling the module <code>main.zig</code>.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ex">zig</span> build-exe src/main.zig</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<p>Since we are building an executable, the <code>zig</code> compiler will look for a <code>main()</code> function declared in any of the files that you list after the <code>build-exe</code> command. If the compiler does not find a <code>main()</code> function declared somewhere, a compilation error will be raised, warning about this mistake.</p>
<p>The <code>zig</code> compiler also offers a <code>build-lib</code> and <code>build-obj</code> commands, which work the exact same way as the <code>build-exe</code> command. The only difference is that, they compile your Zig modules into a portable C ABI library, or, into object files, respectively.</p>
<p>In the case of the <code>build-exe</code> command, a binary executable file is created by the <code>zig</code> compiler in the root directory of your project. If we take a look now at the contents of our current directory, with a simple <code>ls</code> command, we can see the binary file called <code>main</code> that was created by the compiler.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ls</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>build.zig  build.zig.zon  main  src</code></pre>
<p>If I execute this binary executable, I get the “Hello World” message in the terminal , as we expected.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">./main</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>Hello, world!</code></pre>
</section>
<section id="sec-compile-run-code" class="level3" data-number="1.2.5">
<h3 data-number="1.2.5" class="anchored" data-anchor-id="sec-compile-run-code"><span class="header-section-number">1.2.5</span> Compile and execute at the same time</h3>
<p>In the previous section, I presented the <code>zig build-exe</code> command, which compiles Zig modules into an executable file. However, this means that, in order to execute the executable file, we have to run two different commands. First, the <code>zig build-exe</code> command, and then, we call the executable file created by the compiler.</p>
<p>But what if we wanted to perform these two steps, all at once, in a single command? We can do that by using the <code>zig run</code> command.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ex">zig</span> run src/main.zig</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>Hello, world!</code></pre>
</section>
<section id="important-note-for-windows-users" class="level3" data-number="1.2.6">
<h3 data-number="1.2.6" class="anchored" data-anchor-id="important-note-for-windows-users"><span class="header-section-number">1.2.6</span> Important note for Windows users</h3>
<p>First of all, this is a Windows-specific thing, and, therefore, does not apply to other operating systems, such as Linux and macOS. In summary, if you have a piece of Zig code that includes some global variables whose initialization rely on runtime resources, then, you might have some troubles while trying to compile this Zig code on Windows.</p>
<p>An example of that is accessing the <code>stdout</code> (i.e., the <em>standard output</em> of your system), which is usually done in Zig by using the expression <code>std.fs.File.stdout()</code>. If you use this expression to instantiate a global variable in a Zig module, then, the compilation of your Zig code will very likely fail on Windows, with an “unable to evaluate comptime expression” error message.</p>
<p>This failure in the compilation process happens because all global variables in Zig are initialized at <em>compile-time</em>. However, on Windows, operations like accessing the <code>stdout</code> (or opening a file) depend on resources that are available only at <em>runtime</em> (you will learn more about compile-time versus runtime in <a href="01-memory.html#sec-compile-time" class="quarto-xref"><span>Section 3.1.1</span></a>).</p>
<p>For example, if you try to compile this code example on Windows, you will likely get the error message exposed below:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="co">// ERROR! Compile-time error that emerges from</span></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="co">// this next line, on the `stdout` object</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a>    _ = <span class="kw">try</span> stdout.write(<span class="st">"Hello</span><span class="sc">\n</span><span class="st">"</span>);</span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>t.zig:2107:28: error: unable to evaluate comptime expression
    break :blk asm {
               ^~~</code></pre>
<p>To avoid this problem on Windows, we need to force the <code>zig</code> compiler to instantiate this <code>stdout</code> object only at runtime, instead of instantiating it at compile-time. We can achieve that by simply moving the expression to a function body.</p>
<p>This solves the problem because all expressions that are inside a function body in Zig are evaluated only at runtime, unless you use the <code>comptime</code> keyword explicitly to change this behaviour. You will learn more about this <code>comptime</code> keyword in <a href="10-stack-project.html#sec-comptime" class="quarto-xref"><span>Section 12.1</span></a>.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>    <span class="co">// SUCCESS: Stdout initialized at runtime.</span></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a>    _ = <span class="kw">try</span> stdout.write(<span class="st">"Hello</span><span class="sc">\n</span><span class="st">"</span>);</span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Hello</code></pre>
</div>
</div>
<p>You can read more details about this Windows-specific limitation in a couple of GitHub issues opened at the official Zig repository. More specifically, the issues 17186 <a href="#fn7" class="footnote-ref" id="fnref7" role="doc-noteref"><sup>7</sup></a> and 19864 <a href="#fn8" class="footnote-ref" id="fnref8" role="doc-noteref"><sup>8</sup></a>.</p>
</section>
<section id="sec-compile-project" class="level3" data-number="1.2.7">
<h3 data-number="1.2.7" class="anchored" data-anchor-id="sec-compile-project"><span class="header-section-number">1.2.7</span> Compiling the entire project</h3>
<p>Just as I described in <a href="#sec-project-files" class="quarto-xref"><span>Section 1.2.1</span></a>, as our project grows in size and complexity, we usually prefer to organize the compilation and build process of the project into a build script, using some sort of “build system”.</p>
<p>In other words, as our project grows in size and complexity, the <code>build-exe</code>, <code>build-lib</code> and <code>build-obj</code> commands become harder to use directly. Because then, we start to list multiple and multiple modules at the same time. We also start to add built-in compilation flags to customize the build process for our needs, etc. It becomes a lot of work to write the necessary commands by hand.</p>
<p>In C/C++ projects, programmers normally opt to use CMake, Ninja, <code>Makefile</code> or <code>configure</code> scripts to organize this process. However, in Zig, we have a native build system in the language itself. So, we can write build scripts in Zig to compile and build Zig projects. Then, all we need to do, is to call the <code>zig build</code> command to build our project.</p>
<p>So, when you execute the <code>zig build</code> command, the <code>zig</code> compiler will search for a Zig module named <code>build.zig</code> inside your current directory, which should be your build script, containing the necessary code to compile and build your project. If the compiler does find this <code>build.zig</code> file in your directory, then, the compiler will essentially execute a <code>zig run</code> command over this <code>build.zig</code> file, to compile and execute this build script, which in turn, will compile and build your entire project.</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="ex">zig</span> build</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<p>After you execute this “build project” command, a <code>zig-out</code> directory is created in the root of your project directory, where you can find the binary executables and libraries created from your Zig modules accordingly to the build commands that you specified at <code>build.zig</code>. We will talk more about the build system in Zig later in this book.</p>
<p>In the example below, I’m executing the binary executable named <code>hello_world</code> that was generated by the compiler after the <code>zig build</code> command.</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="ex">./zig-out/bin/hello_world</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<pre><code>Hello, world!</code></pre>
</section>
</section>
<section id="how-to-learn-zig" class="level2" data-number="1.3">
<h2 data-number="1.3" class="anchored" data-anchor-id="how-to-learn-zig"><span class="header-section-number">1.3</span> How to learn Zig?</h2>
<p>What are the best strategies to learn Zig? First of all, of course this book will help you a lot on your journey through Zig. But you will also need some extra resources if you want to be really good at Zig.</p>
<p>As a first tip, you can join a community with Zig programmers to get some help , when you need it:</p>
<ul>
<li>Reddit forum: <a href="https://www.reddit.com/r/Zig/" class="uri">https://www.reddit.com/r/Zig/</a>;</li>
<li>Ziggit community: <a href="https://ziggit.dev/" class="uri">https://ziggit.dev/</a>;</li>
<li>Discord, Slack, Telegram, and others: <a href="https://github.com/ziglang/zig/wiki/Community" class="uri">https://github.com/ziglang/zig/wiki/Community</a>;</li>
</ul>
<p>Now, one of the best ways to learn Zig is to simply read Zig code. Try to read Zig code often, and things will become more clear. A C/C++ programmer would also probably give you this same tip. Because this strategy really works!</p>
<p>Now, where can you find Zig code to read? I personally think that, the best way of reading Zig code is to read the source code of the Zig Standard Library. The Zig Standard Library is available at the <a href="https://github.com/ziglang/zig/tree/master/lib/std"><code>lib/std</code> folder</a><a href="#fn9" class="footnote-ref" id="fnref9" role="doc-noteref"><sup>9</sup></a> on the official GitHub repository of Zig. Access this folder, and start exploring the Zig modules.</p>
<p>Also, a great alternative is to read code from other large Zig codebases, such as:</p>
<ol type="1">
<li>the <a href="https://github.com/oven-sh/bun">Javascript runtime Bun</a><a href="#fn10" class="footnote-ref" id="fnref10" role="doc-noteref"><sup>10</sup></a>.</li>
<li>the <a href="https://github.com/hexops/mach">game engine Mach</a><a href="#fn11" class="footnote-ref" id="fnref11" role="doc-noteref"><sup>11</sup></a>.</li>
<li>a <a href="https://github.com/cgbur/llama2.zig/tree/main">LLama 2 LLM model implementation in Zig</a><a href="#fn12" class="footnote-ref" id="fnref12" role="doc-noteref"><sup>12</sup></a>.</li>
<li>the <a href="https://github.com/tigerbeetle/tigerbeetle">financial transactions database <code>tigerbeetle</code></a><a href="#fn13" class="footnote-ref" id="fnref13" role="doc-noteref"><sup>13</sup></a>.</li>
<li>the <a href="https://github.com/Hejsil/zig-clap">command-line arguments parser <code>zig-clap</code></a><a href="#fn14" class="footnote-ref" id="fnref14" role="doc-noteref"><sup>14</sup></a>.</li>
<li>the <a href="https://github.com/capy-ui/capy">UI framework <code>capy</code></a><a href="#fn15" class="footnote-ref" id="fnref15" role="doc-noteref"><sup>15</sup></a>.</li>
<li>the <a href="https://github.com/zigtools/zls">Language Protocol implementation for Zig, <code>zls</code></a><a href="#fn16" class="footnote-ref" id="fnref16" role="doc-noteref"><sup>16</sup></a>.</li>
<li>the <a href="https://github.com/mitchellh/libxev">event-loop library <code>libxev</code></a><a href="#fn17" class="footnote-ref" id="fnref17" role="doc-noteref"><sup>17</sup></a>.</li>
</ol>
<p>All these assets are available on GitHub, and this is great, because we can use the GitHub search bar to our advantage, to find Zig code that fits our description. For example, you can always include <code>lang:Zig</code> in the GitHub search bar when you are searching for a particular pattern. This will limit the search to only Zig modules.</p>
<p>Also, a great alternative is to consult online resources and documentation. Here is a quick list of resources that I personally use from time to time to learn more about the language each day:</p>
<ul>
<li>Zig Language Reference: <a href="https://ziglang.org/documentation/master/" class="uri">https://ziglang.org/documentation/master/</a>;</li>
<li>Zig Standard Library Reference: <a href="https://ziglang.org/documentation/master/std/" class="uri">https://ziglang.org/documentation/master/std/</a>;</li>
<li>Zig Guide: <a href="https://zig.guide/" class="uri">https://zig.guide/</a>;</li>
<li>Karl Seguin Blog: <a href="https://www.openmymind.net/" class="uri">https://www.openmymind.net/</a>;</li>
<li>Zig News: <a href="https://zig.news/" class="uri">https://zig.news/</a>;</li>
<li>Read the code written by one of the Zig core team members: <a href="https://github.com/kubkon" class="uri">https://github.com/kubkon</a>;</li>
<li>Some livecoding sessions are transmitted in the Zig Showtime Youtube Channel: <a href="https://www.youtube.com/@ZigSHOWTIME/videos" class="uri">https://www.youtube.com/@ZigSHOWTIME/videos</a>;</li>
</ul>
<p>Another great strategy to learn Zig, or honestly, to learn any language you want, is to practice it by solving exercises. For example, there is a famous repository in the Zig community called <a href="https://ziglings.org">Ziglings</a><a href="#fn18" class="footnote-ref" id="fnref18" role="doc-noteref"><sup>18</sup></a> , which contains more than 100 small exercises that you can solve. It’s a repository of tiny programs written in Zig that are currently broken, and your responsibility is to fix these programs, and make them work again.</p>
<p>A famous tech YouTuber known as <em>The Primeagen</em> also posted some videos (on YouTube) where he solves these exercises from Ziglings. The first video is named <a href="https://www.youtube.com/watch?v=OPuztQfM3Fg&amp;t=2524s&amp;ab_channel=TheVimeagen">“Trying Zig Part 1”</a><a href="#fn19" class="footnote-ref" id="fnref19" role="doc-noteref"><sup>19</sup></a>.</p>
<p>Another great alternative, is to solve the <a href="https://adventofcode.com/">Advent of Code exercises</a><a href="#fn20" class="footnote-ref" id="fnref20" role="doc-noteref"><sup>20</sup></a>. There are people that already took the time to learn and solve the exercises, and they posted their solutions on GitHub as well, so, in case you need some resource to compare while solving the exercises, you can look at these two repositories:</p>
<ul>
<li><a href="https://github.com/SpexGuy/Zig-AoC-Template" class="uri">https://github.com/SpexGuy/Zig-AoC-Template</a>;</li>
<li><a href="https://github.com/fjebaker/advent-of-code-2022" class="uri">https://github.com/fjebaker/advent-of-code-2022</a>;</li>
</ul>
</section>
<section id="sec-assignments" class="level2" data-number="1.4">
<h2 data-number="1.4" class="anchored" data-anchor-id="sec-assignments"><span class="header-section-number">1.4</span> Creating new objects in Zig (i.e., identifiers)</h2>
<p>Let’s talk more about objects in Zig. Readers that have past experience with other programming languages might know this concept through a different name, such as: “variable” or “identifier”. In this book, I choose to use the term “object” to refer to this concept.</p>
<p>To create a new object (or a new “identifier”) in Zig, we use the keywords <code>const</code> or <code>var</code>. These keywords specify if the object that you are creating is mutable or not. If you use <code>const</code>, then the object you are creating is a constant (or immutable) object, which means that once you declare this object, you can no longer change the value stored inside this object.</p>
<p>On the other side, if you use <code>var</code>, then, you are creating a variable (or mutable) object. You can change the value of this object as many times you want. Using the keyword <code>var</code> in Zig is similar to using the keywords <code>let mut</code> in Rust.</p>
<section id="constant-objects-vs-variable-objects" class="level3" data-number="1.4.1">
<h3 data-number="1.4.1" class="anchored" data-anchor-id="constant-objects-vs-variable-objects"><span class="header-section-number">1.4.1</span> Constant objects vs variable objects</h3>
<p>In the code example below, we are creating a new constant object called <code>age</code>. This object stores a number representing the age of someone. However, this code example does not compile successfully. Because on the next line of code, we are trying to change the value of the object <code>age</code> to 25.</p>
<p>The <code>zig</code> compiler detects that we are trying to change the value of an object/identifier that is constant, and because of that, the compiler will raise a compilation error, warning us about the mistake.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb21"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> age = <span class="dv">24</span>;</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="co">// The line below is not valid!</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>age = <span class="dv">25</span>;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>t.zig:10:5: error: cannot assign to constant
    age = 25;
      ~~^~~</code></pre>
<p>So, if you want to change the value of your object, you need to transform your immutable (or “constant”) object into a mutable (or “variable”) object. You can do that by using the <code>var</code> keyword. This keyword stands for “variable”, and when you apply this keyword to some object, you are telling the Zig compiler that the value associated with this object might change at some point.</p>
<p>Thus, if we come back to the previous example, and change the declaration of the <code>age</code> object to use the <code>var</code> keyword, then, the program gets compiled successfully. Because now, the <code>zig</code> compiler detects that we are changing the value of an object that allows this behaviour, because it’s a “variable object”.</p>
<p>However, if you take a look at the example below, you will notice that we have not only declared the <code>age</code> object with the <code>var</code> keyword, but we also have explicitly annotated the data type of the <code>age</code> object with the <code>u8</code> type this time. The basic idea is, when we use a variable/mutable object, the Zig compiler ask for us to be more explicit with what we want, to be more clear about what our code does. This translates into being more explicit about the data types that we want to use in our objects.</p>
<p>Therefore, if you transform your object into a variable/mutable object, just remember to always annotate the type of the object explicitly in your code. Otherwise, the Zig compiler might raise a compilation error, asking you to transform your object back into a <code>const</code> object, or, to give your object an “explicit type”.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb23"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> age: <span class="dt">u8</span> = <span class="dv">24</span>;</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a>age = <span class="dv">25</span>;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="declaring-without-an-initial-value" class="level3" data-number="1.4.2">
<h3 data-number="1.4.2" class="anchored" data-anchor-id="declaring-without-an-initial-value"><span class="header-section-number">1.4.2</span> Declaring without an initial value</h3>
<p>By default, when you declare a new object in Zig, you must give it an initial value. In other words, this means that we have to declare, and, at the same time, initialize every object we create in our source code.</p>
<p>On the other hand, you can, in fact, declare a new object in your source code, and not give it an explicit value. But we need to use a special keyword for that, which is the <code>undefined</code> keyword.</p>
<p>It’s important to emphasize that, you should avoid using <code>undefined</code> as much as possible. Because when you use this keyword, you leave your object uninitialized, and, as a consequence, if for some reason, your code uses this object while it’s uninitialized, then, you will definitely have undefined behaviour and major bugs in your program.</p>
<p>In the example below, I’m declaring the <code>age</code> object again. But this time, I do not give it an initial value. The variable is only initialized at the second line of code, where I store the number 25 in this object.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> age: <span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a>age = <span class="dv">25</span>;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Having these points in mind, just remember that you should avoid as much as possible to use <code>undefined</code> in your code. Always declare and initialize your objects. Because this gives you much more safety in your program. But in case you really need to declare an object without initializing it… the <code>undefined</code> keyword is the way to do it in Zig.</p>
</section>
<section id="there-is-no-such-thing-as-unused-objects" class="level3" data-number="1.4.3">
<h3 data-number="1.4.3" class="anchored" data-anchor-id="there-is-no-such-thing-as-unused-objects"><span class="header-section-number">1.4.3</span> There is no such thing as unused objects</h3>
<p>Every object (being constant or variable) that you declare in Zig <strong>must be used in some way</strong>. You can give this object to a function call, as a function argument, or, you can use it in another expression to calculate the value of another object, or, you can call a method that belongs to this particular object.</p>
<p>It doesn’t matter in which way you use it. As long as you use it. If you try to break this rule, i.e., if your try to declare a object, but not use it, the <code>zig</code> compiler will not compile your Zig source code, and it will issue a error message warning that you have unused objects in your code.</p>
<p>Let’s demonstrate this with an example. In the source code below, we declare a constant object called <code>age</code>. If you try to compile a simple Zig program with this line of code below, the compiler will return an error as demonstrated below:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> age = <span class="dv">15</span>;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>t.zig:4:11: error: unused local constant
    const age = 15;
          ^~~</code></pre>
<p>Everytime you declare a new object in Zig, you have two choices:</p>
<ol type="1">
<li>you either use the value of this object;</li>
<li>or you explicitly discard the value of the object;</li>
</ol>
<p>To explicitly discard the value of any object (constant or variable), all you need to do is to assign this object to a special character in Zig, which is the underscore (<code>_</code>). When you assign an object to a underscore, like in the example below, the <code>zig</code> compiler will automatically discard the value of this particular object.</p>
<p>You can see in the example below that, this time, the compiler did not complain about any “unused constant”, and successfully compiled our source code.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb27"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a><span class="co">// It compiles!</span></span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> age = <span class="dv">15</span>;</span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a>_ = age;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now, remember, everytime you assign a particular object to the underscore, this object is essentially destroyed. It’s discarded by the compiler. This means that you can no longer use this object further in your code. It doesn’t exist anymore.</p>
<p>So if you try to use the constant <code>age</code> in the example below, after we discarded it, you will get a loud error message from the compiler (talking about a “pointless discard”) warning you about this mistake.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="co">// It does not compile.</span></span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> age = <span class="dv">15</span>;</span>
<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a>_ = age;</span>
<span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a><span class="co">// Using a discarded value!</span></span>
<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a>std.debug.print(<span class="st">"{d}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>age + <span class="dv">2</span><span class="op">}</span>);</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>t.zig:7:5: error: pointless discard
    of local constant</code></pre>
<p>This same rule applies to variable objects. Every variable object must also be used in some way. And if you assign a variable object to the underscore, this object also gets discarded, and you can no longer use this object.</p>
</section>
<section id="you-must-mutate-every-variable-objects" class="level3" data-number="1.4.4">
<h3 data-number="1.4.4" class="anchored" data-anchor-id="you-must-mutate-every-variable-objects"><span class="header-section-number">1.4.4</span> You must mutate every variable objects</h3>
<p>Every variable object that you create in your source code must be mutated at some point. In other words, if you declare an object as a variable object, with the keyword <code>var</code>, and you do not change the value of this object at some point in the future, the <code>zig</code> compiler will detect this, and it will raise an error warning you about this mistake.</p>
<p>The concept behind this is that every object you create in Zig should be preferably a constant object, unless you really need an object whose value will change during the execution of your program.</p>
<p>So, if I try to declare a variable object such as <code>where_i_live</code> below, and I do not change the value of this object in some way, the <code>zig</code> compiler raises an error message with the phrase “variable is never mutated”.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> where_i_live = <span class="st">"Belo Horizonte"</span>;</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a>_ = where_i_live;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>t.zig:7:5: error: local variable is never mutated
t.zig:7:5: note: consider using 'const'</code></pre>
</section>
</section>
<section id="sec-primitive-data-types" class="level2" data-number="1.5">
<h2 data-number="1.5" class="anchored" data-anchor-id="sec-primitive-data-types"><span class="header-section-number">1.5</span> Primitive Data Types</h2>
<p>Zig has many different primitive data types available for you to use. You can see the full list of available data types at the official <a href="https://ziglang.org/documentation/master/#Primitive-Types">Language Reference page</a><a href="#fn21" class="footnote-ref" id="fnref21" role="doc-noteref"><sup>21</sup></a>.</p>
<p>But here is a quick list:</p>
<ul>
<li>Unsigned integers: <code>u8</code>, 8-bit integer; <code>u16</code>, 16-bit integer; <code>u32</code>, 32-bit integer; <code>u64</code>, 64-bit integer; <code>u128</code>, 128-bit integer.</li>
<li>Signed integers: <code>i8</code>, 8-bit integer; <code>i16</code>, 16-bit integer; <code>i32</code>, 32-bit integer; <code>i64</code>, 64-bit integer; <code>i128</code>, 128-bit integer.</li>
<li>Float number: <code>f16</code>, 16-bit floating point; <code>f32</code>, 32-bit floating point; <code>f64</code>, 64-bit floating point; <code>f128</code>, 128-bit floating point;</li>
<li>Boolean: <code>bool</code>, represents true or false values.</li>
<li>C ABI compatible types: <code>c_long</code>, <code>c_char</code>, <code>c_short</code>, <code>c_ushort</code>, <code>c_int</code>, <code>c_uint</code>, and many others.</li>
<li>Pointer sized integers: <code>isize</code> and <code>usize</code>.</li>
</ul>
</section>
<section id="sec-arrays" class="level2" data-number="1.6">
<h2 data-number="1.6" class="anchored" data-anchor-id="sec-arrays"><span class="header-section-number">1.6</span> Arrays</h2>
<p>You create arrays in Zig by using a syntax that resembles the C syntax. First, you specify the size of the array (i.e., the number of elements that will be stored in the array) you want to create inside a pair of brackets.</p>
<p>Then, you specify the data type of the elements that will be stored inside this array. All elements present in an array in Zig must have the same data type. For example, you cannot mix elements of type <code>f32</code> with elements of type <code>i32</code> in the same array.</p>
<p>After that, you simply list the values that you want to store in this array inside a pair of curly braces. In the example below, I am creating two constant objects that contain different arrays. The first object contains an array of 4 integer values, while the second object, an array of 3 floating point values.</p>
<p>Now, you should notice that in the object <code>ls</code>, I am not explicitly specifying the size of the array inside of the brackets. Instead of using a literal value (like the value 4 that I used in the <code>ns</code> object), I am using the special character underscore (<code>_</code>). This syntax tells the <code>zig</code> compiler to fill this field with the number of elements listed inside of the curly braces. So, this syntax <code>[_]</code> is for lazy (or smart) programmers who leave the job of counting how many elements there are in the curly braces for the compiler.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb32"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ns = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ls = [_]<span class="dt">f64</span><span class="op">{</span><span class="fl">432.1</span>, <span class="fl">87.2</span>, <span class="fl">900.05</span><span class="op">}</span>;</span>
<span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a>_ = ns; _ = ls;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>It’s worth noting that these are static arrays, meaning that they cannot grow in size. Once you declare your array, you cannot change the size of it. This is very common in low level languages. Because low level languages normally wants to give you (the programmer) full control over memory, and the way in which arrays are expanded is tightly related to memory management.</p>
<section id="sec-select-array-elem" class="level3" data-number="1.6.1">
<h3 data-number="1.6.1" class="anchored" data-anchor-id="sec-select-array-elem"><span class="header-section-number">1.6.1</span> Selecting elements of the array</h3>
<p>One very common activity is to select specific portions of an array you have in your source code. In Zig, you can select a specific element from your array, by simply providing the index of this particular element inside brackets after the object name. In the example below, I am selecting the third element from the <code>ns</code> array. Notice that Zig is a “zero-index” based language, like C, C++, Rust, Python, and many other languages.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb33"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ns = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb33-2"><a href="#cb33-2" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{d}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span> ns[<span class="dv">2</span>] <span class="op">}</span>);</span>
<span id="cb33-3"><a href="#cb33-3" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>12</code></pre>
</div>
</div>
<p>In contrast, you can also select specific slices (or sections) of your array, by using a range selector. Some programmers also call these selectors of “slice selectors”, and they also exist in Rust, and have the exact same syntax as in Zig. Anyway, a range selector is a special expression in Zig that defines a range of indexes, and it has the syntax <code>start..end</code>.</p>
<p>In the example below, at the second line of code, the <code>sl</code> object stores a slice (or a portion) of the <code>ns</code> array. More precisely, the elements at index 1 and 2 in the <code>ns</code> array.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb35"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb35-1"><a href="#cb35-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ns = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb35-2"><a href="#cb35-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> sl = ns[<span class="dv">1</span>..<span class="dv">3</span>];</span>
<span id="cb35-3"><a href="#cb35-3" aria-hidden="true" tabindex="-1"></a>_ = sl;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>When you use the <code>start..end</code> syntax, the “end tail” of the range selector is non-inclusive, meaning that, the index at the end is not included in the range that is selected from the array. Therefore, the syntax <code>start..end</code> actually means <code>start..end - 1</code> in practice.</p>
<p>You can for example, create a slice that goes from the first to the last elements of the array, by using <code>ar[0..ar.len]</code> syntax In other words, it’s a slice that accesses all elements in the array.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb36"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb36-1"><a href="#cb36-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ar = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb36-2"><a href="#cb36-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> sl = ar[<span class="dv">0</span>..ar.len];</span>
<span id="cb36-3"><a href="#cb36-3" aria-hidden="true" tabindex="-1"></a>_ = sl;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>You can also use the syntax <code>start..</code> in your range selector. Which tells the <code>zig</code> compiler to select the portion of the array that begins at the <code>start</code> index until the last element of the array. In the example below, we are selecting the range from index 1 until the end of the array.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb37"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ns = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb37-2"><a href="#cb37-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> sl = ns[<span class="dv">1</span>..];</span>
<span id="cb37-3"><a href="#cb37-3" aria-hidden="true" tabindex="-1"></a>_ = sl;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="more-on-slices" class="level3" data-number="1.6.2">
<h3 data-number="1.6.2" class="anchored" data-anchor-id="more-on-slices"><span class="header-section-number">1.6.2</span> More on slices</h3>
<p>As we discussed before, in Zig, you can select specific portions of an existing array. This is called <em>slicing</em> in Zig <span class="citation" data-cites="zigguide">(<a href="references.html#ref-zigguide" role="doc-biblioref">Sobeston 2024</a>)</span>, because when you select a portion of an array, you are creating a slice object from that array.</p>
<p>A slice object is essentially a pointer object accompanied by a length number. The pointer object points to the first element in the slice, and the length number tells the <code>zig</code> compiler how many elements there are in this slice.</p>
<blockquote class="blockquote">
<p>Slices can be thought of as a pair of <code>[*]T</code> (the pointer to the data) and a <code>usize</code> (the element count) <span class="citation" data-cites="zigguide">(<a href="references.html#ref-zigguide" role="doc-biblioref">Sobeston 2024</a>)</span>.</p>
</blockquote>
<p>Through the pointer contained inside the slice you can access the elements (or values) that are inside this range (or portion) that you selected from the original array. But the length number (which you can access through the <code>len</code> property of your slice object) is the really big improvement (over C arrays for example) that Zig brings to the table here.</p>
<p>Because with this length number the <code>zig</code> compiler can easily check if you are trying to access an index that is out of the bounds of this particular slice, or, if you are causing any buffer overflow problems. In the example below, we access the <code>len</code> property of the slice <code>sl</code>, which tells us that this slice has 2 elements in it.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb38"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb38-1"><a href="#cb38-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> ns = [<span class="dv">4</span>]<span class="dt">u8</span><span class="op">{</span><span class="dv">48</span>, <span class="dv">24</span>, <span class="dv">12</span>, <span class="dv">6</span><span class="op">}</span>;</span>
<span id="cb38-2"><a href="#cb38-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> sl = ns[<span class="dv">1</span>..<span class="dv">3</span>];</span>
<span id="cb38-3"><a href="#cb38-3" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{d}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>sl.len<span class="op">}</span>);</span>
<span id="cb38-4"><a href="#cb38-4" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>2</code></pre>
</div>
</div>
</section>
<section id="array-operators" class="level3" data-number="1.6.3">
<h3 data-number="1.6.3" class="anchored" data-anchor-id="array-operators"><span class="header-section-number">1.6.3</span> Array operators</h3>
<p>There are two array operators available in Zig that are very useful. The array concatenation operator (<code>++</code>), and the array multiplication operator (<code>**</code>). As the name suggests, these are array operators.</p>
<p>One important detail about these two operators is that they work only when both operands have a size (or “length”) that is compile-time known. We are going to talk more about the differences between “compile-time known” and “runtime known” in <a href="01-memory.html#sec-compile-time" class="quarto-xref"><span>Section 3.1.1</span></a>. But for now, keep this information in mind, that you cannot use these operators in every situation.</p>
<p>In summary, the <code>++</code> operator creates a new array that is the concatenation, of both arrays provided as operands. So, the expression <code>a ++ b</code> produces a new array which contains all the elements from arrays <code>a</code> and <code>b</code>.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb40"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb40-1"><a href="#cb40-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> a = [_]<span class="dt">u8</span><span class="op">{</span><span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span><span class="op">}</span>;</span>
<span id="cb40-2"><a href="#cb40-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> b = [_]<span class="dt">u8</span><span class="op">{</span><span class="dv">4</span>,<span class="dv">5</span><span class="op">}</span>;</span>
<span id="cb40-3"><a href="#cb40-3" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> c = a ++ b;</span>
<span id="cb40-4"><a href="#cb40-4" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>c<span class="op">}</span>);</span>
<span id="cb40-5"><a href="#cb40-5" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>{ 1, 2, 3, 4, 5 }</code></pre>
</div>
</div>
<p>This <code>++</code> operator is particularly useful to concatenate strings together. Strings in Zig are described in depth in <a href="#sec-zig-strings" class="quarto-xref"><span>Section 1.8</span></a>. In summary, a string object in Zig is essentially an array of bytes. So, you can use this array concatenation operator to effectively concatenate strings together.</p>
<p>In contrast, the <code>**</code> operator is used to replicate an array multiple times. In other words, the expression <code>a ** 3</code> creates a new array which contains the elements of the array <code>a</code> repeated 3 times.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb42"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb42-1"><a href="#cb42-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> a = [_]<span class="dt">u8</span><span class="op">{</span><span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span><span class="op">}</span>;</span>
<span id="cb42-2"><a href="#cb42-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> c = a ** <span class="dv">2</span>;</span>
<span id="cb42-3"><a href="#cb42-3" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>c<span class="op">}</span>);</span>
<span id="cb42-4"><a href="#cb42-4" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>{ 1, 2, 3, 1, 2, 3 }</code></pre>
</div>
</div>
</section>
<section id="runtime-versus-compile-time-known-length-in-slices" class="level3" data-number="1.6.4">
<h3 data-number="1.6.4" class="anchored" data-anchor-id="runtime-versus-compile-time-known-length-in-slices"><span class="header-section-number">1.6.4</span> Runtime versus compile-time known length in slices</h3>
<p>We are going to talk a lot about the differences between compile-time known and runtime known across this book, especially in <a href="01-memory.html#sec-compile-time" class="quarto-xref"><span>Section 3.1.1</span></a>. But the basic idea is that a thing is compile-time known, when we know everything (the value, the attributes and the characteristics) about this thing at compile-time. In contrast, a runtime known thing is when the exact value of a thing is calculated only at runtime. Therefore, we don’t know the value of this thing at compile-time, only at runtime.</p>
<p>We have learned in <a href="#sec-select-array-elem" class="quarto-xref"><span>Section 1.6.1</span></a> that slices are created by using a <em>range selector</em>, which represents a range of indexes. When this “range of indexes” (i.e., both the start and the end of this range) is known at compile-time, the slice object that gets created is actually, under the hood, just a single-item pointer to an array.</p>
<p>You don’t need to precisely understand what that means now. We are going to talk a lot about pointers in <a href="05-pointers.html" class="quarto-xref"><span>Chapter 6</span></a>. For now, just understand that, when the range of indexes is known at compile-time, the slice that gets created is just a pointer to an array, accompanied by a length value that tells the size of the slice.</p>
<p>If you have a slice object like this, i.e., a slice that has a compile-time known range, you can use common pointer operations over this slice object. For example, you can dereference the pointer of this slice, by using the <code>.*</code> method, like you would do on a normal pointer object.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb44"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb44-1"><a href="#cb44-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> arr1 = [<span class="dv">10</span>]<span class="dt">u64</span> <span class="op">{</span></span>
<span id="cb44-2"><a href="#cb44-2" aria-hidden="true" tabindex="-1"></a>    <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>,</span>
<span id="cb44-3"><a href="#cb44-3" aria-hidden="true" tabindex="-1"></a>    <span class="dv">6</span>, <span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>, <span class="dv">10</span></span>
<span id="cb44-4"><a href="#cb44-4" aria-hidden="true" tabindex="-1"></a><span class="op">}</span>;</span>
<span id="cb44-5"><a href="#cb44-5" aria-hidden="true" tabindex="-1"></a><span class="co">// This slice has a compile-time known range.</span></span>
<span id="cb44-6"><a href="#cb44-6" aria-hidden="true" tabindex="-1"></a><span class="co">// Because we know both the start and end of the range.</span></span>
<span id="cb44-7"><a href="#cb44-7" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> slice = arr1[<span class="dv">1</span>..<span class="dv">4</span>];</span>
<span id="cb44-8"><a href="#cb44-8" aria-hidden="true" tabindex="-1"></a>_ = slice;</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>On the other hand, if the range of indexes is not known at compile time, then, the slice object that gets created is not a pointer anymore, and, thus, it does not support pointer operations. For example, maybe the start index is known at compile time, but the end index is not. In such case, the range of the slice becomes runtime known only.</p>
<p>In the example below, we are reading a file, and then, we try to create a slice object that covers the entire buffer that contains the contents of this file. This is obviously an example of a runtime known range, because the end index of the range is not known at compile time.</p>
<p>In other words, the end index of the range is the size of the array <code>file_contents</code>. However, the size of <code>file_contents</code> is not known at compile time. Because we don’t know how many bytes are stored inside this <code>shop-list.txt</code> file. And because this is a file, someone might edit this file tomorrow and add more lines or remove lines from it. Therefore, the size of this file might vary drastically from one execution to another.</p>
<p>Now, if the file size can vary from one run to another, then, we can conclude that the value of the expression <code>file_contents.len</code> exposed in the example below can also vary from one run to another. As consequence, the value of the expression <code>file_contents.len</code> is runtime-known only, and, as a consequence of that, the range <code>0..file_contents.len</code> is also runtime-known only.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb45"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb45-1"><a href="#cb45-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb45-2"><a href="#cb45-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> builtin = <span class="bu">@import</span>(<span class="st">"builtin"</span>);</span>
<span id="cb45-3"><a href="#cb45-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb45-4"><a href="#cb45-4" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> read_file(allocator: std.mem.Allocator, path: []<span class="kw">const</span> <span class="dt">u8</span>) ![]<span class="dt">u8</span> <span class="op">{</span></span>
<span id="cb45-5"><a href="#cb45-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> file = <span class="kw">try</span> std.fs.cwd().openFile(path, .<span class="op">{}</span>);</span>
<span id="cb45-6"><a href="#cb45-6" aria-hidden="true" tabindex="-1"></a>    <span class="kw">defer</span> file.close();</span>
<span id="cb45-7"><a href="#cb45-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb45-8"><a href="#cb45-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> file_buffer = <span class="kw">try</span> allocator.alloc(<span class="dt">u8</span>, <span class="dv">1024</span>);</span>
<span id="cb45-9"><a href="#cb45-9" aria-hidden="true" tabindex="-1"></a>    <span class="bu">@memset</span>(file_buffer[<span class="dv">0</span>..], <span class="dv">0</span>);</span>
<span id="cb45-10"><a href="#cb45-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb45-11"><a href="#cb45-11" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> nbytes = <span class="kw">try</span> file.read(file_buffer[<span class="dv">0</span>..]);</span>
<span id="cb45-12"><a href="#cb45-12" aria-hidden="true" tabindex="-1"></a>    <span class="kw">return</span> file_buffer[<span class="dv">0</span>..nbytes];</span>
<span id="cb45-13"><a href="#cb45-13" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb45-14"><a href="#cb45-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb45-15"><a href="#cb45-15" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb45-16"><a href="#cb45-16" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> gpa = std.heap.GeneralPurposeAllocator(.<span class="op">{}</span>)<span class="op">{}</span>;</span>
<span id="cb45-17"><a href="#cb45-17" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> allocator = gpa.allocator();</span>
<span id="cb45-18"><a href="#cb45-18" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> path = <span class="st">"../ZigExamples/file-io/shop-list.txt"</span>;</span>
<span id="cb45-19"><a href="#cb45-19" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> file_contents = <span class="kw">try</span> read_file(allocator, path);</span>
<span id="cb45-20"><a href="#cb45-20" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> slice = file_contents[<span class="dv">0</span>..file_contents.len];</span>
<span id="cb45-21"><a href="#cb45-21" aria-hidden="true" tabindex="-1"></a>    _ = slice;</span>
<span id="cb45-22"><a href="#cb45-22" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
</section>
<section id="sec-blocks" class="level2" data-number="1.7">
<h2 data-number="1.7" class="anchored" data-anchor-id="sec-blocks"><span class="header-section-number">1.7</span> Blocks and scopes</h2>
<p>Blocks are created in Zig by a pair of curly braces. A block is just a group of expressions (or statements) contained inside of a pair of curly braces. All of these expressions that are contained inside of this pair of curly braces belongs to the same scope.</p>
<p>In other words, a block just delimits a scope in your code. The objects that you define inside the same block belongs to the same scope, and, therefore, are accessible from within this scope. At the same time, these objects are not accessible outside of this scope. So, you could also say that blocks are used to limit the scope of the objects that you create in your source code. In less technical terms, blocks are used to specify where in your source code you can access whatever object you have in your source code.</p>
<p>So, a block is just a group of expressions contained inside a pair of curly braces. And every block have its own scope separated from the others. The body of a function is a classic example of a block. If statements, for and while loops (and any other structure in the language that uses the pair of curly braces) are also examples of blocks.</p>
<p>This means that, every if statement, or for loop, etc., that you create in your source code has its own separate scope. That is why you can’t access the objects that you defined inside of your for loop (or if statement) in an outer scope, i.e., a scope outside of the for loop. Because you are trying to access an object that belongs to a scope that is different than your current scope.</p>
<p>You can create blocks within blocks, with multiple levels of nesting. You can also (if you want to) give a label to a particular block, with the colon character (<code>:</code>). Just write <code>label:</code> before you open the pair of curly braces that delimits your block. When you label a block in Zig, you can use the <code>break</code> keyword to return a value from this block, like as if it was a function’s body. You just write the <code>break</code> keyword, followed by the block label in the format <code>:label</code>, and the expression that defines the value that you want to return.</p>
<p>Like in the example below, where we are returning the value from the <code>y</code> object from the block <code>add_one</code>, and saving the result inside the <code>x</code> object.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb46"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb46-1"><a href="#cb46-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> y: <span class="dt">i32</span> = <span class="dv">123</span>;</span>
<span id="cb46-2"><a href="#cb46-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> x = add_one: <span class="op">{</span></span>
<span id="cb46-3"><a href="#cb46-3" aria-hidden="true" tabindex="-1"></a>    y += <span class="dv">1</span>;</span>
<span id="cb46-4"><a href="#cb46-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">break</span> :add_one y;</span>
<span id="cb46-5"><a href="#cb46-5" aria-hidden="true" tabindex="-1"></a><span class="op">}</span>;</span>
<span id="cb46-6"><a href="#cb46-6" aria-hidden="true" tabindex="-1"></a><span class="kw">if</span> (x == <span class="dv">124</span> <span class="kw">and</span> y == <span class="dv">124</span>) <span class="op">{</span></span>
<span id="cb46-7"><a href="#cb46-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"Hey!"</span>, .<span class="op">{}</span>);</span>
<span id="cb46-8"><a href="#cb46-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb46-9"><a href="#cb46-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Hey!</code></pre>
</div>
</div>
</section>
<section id="sec-zig-strings" class="level2" data-number="1.8">
<h2 data-number="1.8" class="anchored" data-anchor-id="sec-zig-strings"><span class="header-section-number">1.8</span> How strings work in Zig?</h2>
<p>The first project that we are going to build and discuss in this book is a base64 encoder/decoder (<a href="01-base64.html" class="quarto-xref"><span>Chapter 4</span></a>). But in order for us to build such a thing, we need to get a better understanding on how strings work in Zig. So let’s discuss this specific aspect of Zig.</p>
<p>Strings in Zig work very similarly to strings in C, but they come with some extra caveats which adds more safety and efficiency to them. You could also say that Zig simply uses a more modern and safe approach to manage and use strings.</p>
<p>A string in Zig is essentially an array of arbitrary bytes, or, more specifically, an array of <code>u8</code> values. This very similar to a string in C, which is also interpreted as an array of arbitrary bytes, or, in the case of C, an array of <code>char</code> (which usually represents an unsigned 8-bit integer value in most systems) values.</p>
<p>Now, because a string in Zig is an array, you automatically get the length of the string (i.e.&nbsp;the length of the array) embedded in the value itself. This makes all the difference! Because now, the Zig compiler can use the length value that is embedded in the string to check for “buffer overflow” or “wrong memory access” problems in your code.</p>
<p>To achieve this same kind of safety in C, you have to do a lot of work that kind of seems pointless. So getting this kind of safety is not automatic and much harder to do in C. For example, if you want to track the length of your string throughout your program in C, then, you first need to loop through the array of bytes that represents this string, and find the null element (<code>'\0'</code>) position to discover where exactly the array ends, or, in other words, to find how much elements the array of bytes contain.</p>
<p>To do that, you would need to do something like this in C. In this example, the C string stored in the object <code>array</code> is 25 bytes long:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb48"><pre class="sourceCode c code-with-copy"><code class="sourceCode c"><span id="cb48-1"><a href="#cb48-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;stdio.h&gt;</span></span>
<span id="cb48-2"><a href="#cb48-2" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> main<span class="op">()</span> <span class="op">{</span></span>
<span id="cb48-3"><a href="#cb48-3" aria-hidden="true" tabindex="-1"></a>    <span class="dt">char</span><span class="op">*</span> array <span class="op">=</span> <span class="st">"An example of string in C"</span><span class="op">;</span></span>
<span id="cb48-4"><a href="#cb48-4" aria-hidden="true" tabindex="-1"></a>    <span class="dt">int</span> index <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span>
<span id="cb48-5"><a href="#cb48-5" aria-hidden="true" tabindex="-1"></a>    <span class="cf">while</span> <span class="op">(</span><span class="dv">1</span><span class="op">)</span> <span class="op">{</span></span>
<span id="cb48-6"><a href="#cb48-6" aria-hidden="true" tabindex="-1"></a>        <span class="cf">if</span> <span class="op">(</span>array<span class="op">[</span>index<span class="op">]</span> <span class="op">==</span> <span class="ch">'</span><span class="sc">\0</span><span class="ch">'</span><span class="op">)</span> <span class="op">{</span></span>
<span id="cb48-7"><a href="#cb48-7" aria-hidden="true" tabindex="-1"></a>            <span class="cf">break</span><span class="op">;</span></span>
<span id="cb48-8"><a href="#cb48-8" aria-hidden="true" tabindex="-1"></a>        <span class="op">}</span></span>
<span id="cb48-9"><a href="#cb48-9" aria-hidden="true" tabindex="-1"></a>        index<span class="op">++;</span></span>
<span id="cb48-10"><a href="#cb48-10" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb48-11"><a href="#cb48-11" aria-hidden="true" tabindex="-1"></a>    printf<span class="op">(</span><span class="st">"Number of elements in the array: </span><span class="sc">%d\n</span><span class="st">"</span><span class="op">,</span> index<span class="op">);</span></span>
<span id="cb48-12"><a href="#cb48-12" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>Number of elements in the array: 25</code></pre>
<p>You don’t have this kind of work in Zig. Because the length of the string is always present and accessible in the string value itself. You can easily access the length of the string through the <code>len</code> attribute. As an example, the <code>string_object</code> object below is 43 bytes long:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb50"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb50-1"><a href="#cb50-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb50-2"><a href="#cb50-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb50-3"><a href="#cb50-3" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb50-4"><a href="#cb50-4" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb50-5"><a href="#cb50-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb50-6"><a href="#cb50-6" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb50-7"><a href="#cb50-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> string_object = <span class="st">"This is an example of string literal in Zig"</span>;</span>
<span id="cb50-8"><a href="#cb50-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"{d}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>string_object.len<span class="op">}</span>);</span>
<span id="cb50-9"><a href="#cb50-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb50-10"><a href="#cb50-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>43</code></pre>
</div>
</div>
<p>Another point is that Zig always assumes that the sequence of bytes in your string is UTF-8 encoded. This might not be true for every sequence of bytes you’re working with, but it’s not really Zig’s job to fix the encoding of your strings (you can use <a href="https://www.gnu.org/software/libiconv/"><code>iconv</code></a><a href="#fn22" class="footnote-ref" id="fnref22" role="doc-noteref"><sup>22</sup></a> for that). Today, most of the text in our modern world, especially on the web, should be UTF-8 encoded. So if your string literal is not UTF-8 encoded, then, you will likely have problems in Zig.</p>
<p>Let’s take for example the word “Hello”. In UTF-8, this sequence of characters (H, e, l, l, o) is represented by the sequence of decimal numbers 72, 101, 108, 108, 111. In hexadecimal, this sequence is <code>0x48</code>, <code>0x65</code>, <code>0x6C</code>, <code>0x6C</code>, <code>0x6F</code>. So if I take this sequence of hexadecimal values, and ask Zig to print this sequence of bytes as a sequence of characters (i.e., a string), then, the text “Hello” will be printed into the terminal:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb52"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb52-1"><a href="#cb52-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb52-2"><a href="#cb52-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb52-3"><a href="#cb52-3" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb52-4"><a href="#cb52-4" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb52-5"><a href="#cb52-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb52-6"><a href="#cb52-6" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb52-7"><a href="#cb52-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> bytes = [_]<span class="dt">u8</span><span class="op">{</span><span class="bn">0x48</span>, <span class="bn">0x65</span>, <span class="bn">0x6C</span>, <span class="bn">0x6C</span>, <span class="bn">0x6F</span><span class="op">}</span>;</span>
<span id="cb52-8"><a href="#cb52-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"{s}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>bytes<span class="op">}</span>);</span>
<span id="cb52-9"><a href="#cb52-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb52-10"><a href="#cb52-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Hello</code></pre>
</div>
</div>
<section id="using-a-slice-versus-a-sentinel-terminated-array" class="level3" data-number="1.8.1">
<h3 data-number="1.8.1" class="anchored" data-anchor-id="using-a-slice-versus-a-sentinel-terminated-array"><span class="header-section-number">1.8.1</span> Using a slice versus a sentinel-terminated array</h3>
<p>In memory, all string values in Zig are always stored in the same way. They are simply stored as sequences/arrays of arbitrary bytes. But you can use and access this sequence of bytes in two different ways. You can access this sequence of bytes as:</p>
<ul>
<li>a sentinel-terminated array of <code>u8</code> values.</li>
<li>or as a slice of <code>u8</code> values.</li>
</ul>
<section id="sentinel-terminated-arrays" class="level4" data-number="1.8.1.1">
<h4 data-number="1.8.1.1" class="anchored" data-anchor-id="sentinel-terminated-arrays"><span class="header-section-number">1.8.1.1</span> Sentinel-terminated arrays</h4>
<p>Sentinel-terminated arrays in Zig are described in the Language Reference of Zig<a href="#fn23" class="footnote-ref" id="fnref23" role="doc-noteref"><sup>23</sup></a>. In summary a sentinel-terminated array is just a normal array, but, the difference is that they contain a “sentinel value” at the last index/element of the array. With a sentinel-terminated array you embed both the length of the array, and also, the sentinel value in the type itself of your object.</p>
<p>For example, if you write a string literal value in your code, and ask Zig to print the data type of this value, you usually get a data type in the format <code>*const [n:0]u8</code>. The <code>n</code> in the data type indicates the size of the string (that is the length of the array). The zero after the <code>n:</code> part of the data type is the sentinel value itself.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb54"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb54-1"><a href="#cb54-1" aria-hidden="true" tabindex="-1"></a><span class="co">// This is a string literal value:</span></span>
<span id="cb54-2"><a href="#cb54-2" aria-hidden="true" tabindex="-1"></a>_ = <span class="st">"A literal value"</span>;</span>
<span id="cb54-3"><a href="#cb54-3" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(<span class="st">"A literal value"</span>)<span class="op">}</span>);</span>
<span id="cb54-4"><a href="#cb54-4" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>*const [15:0]u8</code></pre>
</div>
</div>
<p>So, with this data type <code>*const [n:0]u8</code> you are essentially saying that you have an array of <code>u8</code> values of length <code>n</code>, where, the element at the index corresponding to the length <code>n</code> in the array is the number zero. If you really think about this description, you will notice that this is just a fancy way to describe a string in C, which is a null-terminated array of bytes. The <code>NULL</code> value in C is the number zero. So, an array that ends in a null/zero value in C is essentially a sentinel-terminated array in Zig, where the sentinel value of the array is the number zero.</p>
<p>Therefore, a string literal value in Zig is just a pointer to a null-terminated array of bytes (i.e., similar to a C string). But in Zig, a string literal value also embeds the length of the string, and also, the fact that they are “NULL terminated”, into the data type of the value itself.</p>
</section>
<section id="slice" class="level4" data-number="1.8.1.2">
<h4 data-number="1.8.1.2" class="anchored" data-anchor-id="slice"><span class="header-section-number">1.8.1.2</span> Slice</h4>
<p>You can also access and use the arbitrary sequence of bytes that represent your string as a slice of <code>u8</code> values. The majority of functions from the Zig standard library usually receive strings as inputs as slices of <code>u8</code> values (slices were presented in <a href="#sec-arrays" class="quarto-xref"><span>Section 1.6</span></a>).</p>
<p>Thus, you will see a lot of string values with a data type of <code>[]u8</code> or <code>[]const u8</code>, depending if the object where this string is stored is marked as constant with <code>const</code>, or as variable with <code>var</code>. Now, because the string in this case is being interpreted as a slice, this slice is not necessarilly null-terminated, because now, the sentinel value is not mandatory. You can include the null/zero value in the slice if you want to, but there is no need to do it.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb56"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb56-1"><a href="#cb56-1" aria-hidden="true" tabindex="-1"></a><span class="co">// This is a string value being</span></span>
<span id="cb56-2"><a href="#cb56-2" aria-hidden="true" tabindex="-1"></a><span class="co">// interpreted as a slice.</span></span>
<span id="cb56-3"><a href="#cb56-3" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> str: []<span class="kw">const</span> <span class="dt">u8</span> = <span class="st">"A string value"</span>;</span>
<span id="cb56-4"><a href="#cb56-4" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(str)<span class="op">}</span>);</span>
<span id="cb56-5"><a href="#cb56-5" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[]const u8</code></pre>
</div>
</div>
</section>
</section>
<section id="iterating-through-the-string" class="level3" data-number="1.8.2">
<h3 data-number="1.8.2" class="anchored" data-anchor-id="iterating-through-the-string"><span class="header-section-number">1.8.2</span> Iterating through the string</h3>
<p>If you want to see the actual bytes that represents a string in Zig, you can use a <code>for</code> loop to iterate through each byte in the string, and ask Zig to print each byte as a hexadecimal value to the terminal. You do that by using a <code>print()</code> statement with the <code>X</code> formatting specifier, like you would normally do with the <a href="https://cplusplus.com/reference/cstdio/printf/"><code>printf()</code> function</a><a href="#fn24" class="footnote-ref" id="fnref24" role="doc-noteref"><sup>24</sup></a> in C.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb58"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb58-1"><a href="#cb58-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb58-2"><a href="#cb58-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb58-3"><a href="#cb58-3" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb58-4"><a href="#cb58-4" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb58-5"><a href="#cb58-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb58-6"><a href="#cb58-6" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb58-7"><a href="#cb58-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> string_object = <span class="st">"This is an example"</span>;</span>
<span id="cb58-8"><a href="#cb58-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"Bytes that represents the string object: "</span>, .<span class="op">{}</span>);</span>
<span id="cb58-9"><a href="#cb58-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">for</span> (string_object) |byte| <span class="op">{</span></span>
<span id="cb58-10"><a href="#cb58-10" aria-hidden="true" tabindex="-1"></a>        <span class="kw">try</span> stdout.print(<span class="st">"{X} "</span>, .<span class="op">{</span>byte<span class="op">}</span>);</span>
<span id="cb58-11"><a href="#cb58-11" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb58-12"><a href="#cb58-12" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.print(<span class="st">"</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{}</span>);</span>
<span id="cb58-13"><a href="#cb58-13" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb58-14"><a href="#cb58-14" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Bytes that represents the string object: 54 68 69 
   73 20 69 73 20 61 6E 20 65 78 61 6D 70 6C 65 </code></pre>
</div>
</div>
</section>
<section id="a-better-look-at-the-object-type" class="level3" data-number="1.8.3">
<h3 data-number="1.8.3" class="anchored" data-anchor-id="a-better-look-at-the-object-type"><span class="header-section-number">1.8.3</span> A better look at the object type</h3>
<p>Now, we can inspect better the type of objects that Zig create. To check the type of any object in Zig, you can use the <code>@TypeOf()</code> function. If we look at the type of the <code>simple_array</code> object below, you will find that this object is an array of 4 elements. Each element is a signed integer of 32 bits which corresponds to the data type <code>i32</code> in Zig. That is what an object of type <code>[4]i32</code> is.</p>
<p>But if we look closely at the type of the string literal value exposed below, you will find that this object is a constant pointer (hence the <code>*const</code> annotation) to an array of 16 elements (or 16 bytes). Each element is a single byte (more precisely, an unsigned 8 bit integer - <code>u8</code>), that is why we have the <code>[16:0]u8</code> portion of the type below, and also, you can see that this is a null-terminated array, because of the zero value after the <code>:</code> character in the data type. In other words, the string literal value exposed below is 16 bytes long.</p>
<p>Now, if we create a pointer to the <code>simple_array</code> object, then, we get a constant pointer to an array of 4 elements (<code>*const [4]i32</code>), which is very similar to the type of the string literal value. This demonstrates that a string literal value in Zig is already a pointer to a null-terminated array of bytes.</p>
<p>Furthermore, if we take a look at the type of the <code>string_obj</code> object, you will see that it’s a slice object (hence the <code>[]</code> portion of the type) to a sequence of constant <code>u8</code> values (hence the <code>const u8</code> portion of the type).</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb60"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb60-1"><a href="#cb60-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb60-2"><a href="#cb60-2" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb60-3"><a href="#cb60-3" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> simple_array = [_]<span class="dt">i32</span><span class="op">{</span><span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span><span class="op">}</span>;</span>
<span id="cb60-4"><a href="#cb60-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> string_obj: []<span class="kw">const</span> <span class="dt">u8</span> = <span class="st">"A string object"</span>;</span>
<span id="cb60-5"><a href="#cb60-5" aria-hidden="true" tabindex="-1"></a>    std.debug.print(</span>
<span id="cb60-6"><a href="#cb60-6" aria-hidden="true" tabindex="-1"></a>        <span class="st">"Type 1: {}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(simple_array)<span class="op">}</span></span>
<span id="cb60-7"><a href="#cb60-7" aria-hidden="true" tabindex="-1"></a>    );</span>
<span id="cb60-8"><a href="#cb60-8" aria-hidden="true" tabindex="-1"></a>    std.debug.print(</span>
<span id="cb60-9"><a href="#cb60-9" aria-hidden="true" tabindex="-1"></a>        <span class="st">"Type 2: {}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(<span class="st">"A string literal"</span>)<span class="op">}</span></span>
<span id="cb60-10"><a href="#cb60-10" aria-hidden="true" tabindex="-1"></a>    );</span>
<span id="cb60-11"><a href="#cb60-11" aria-hidden="true" tabindex="-1"></a>    std.debug.print(</span>
<span id="cb60-12"><a href="#cb60-12" aria-hidden="true" tabindex="-1"></a>        <span class="st">"Type 3: {}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(&amp;simple_array)<span class="op">}</span></span>
<span id="cb60-13"><a href="#cb60-13" aria-hidden="true" tabindex="-1"></a>    );</span>
<span id="cb60-14"><a href="#cb60-14" aria-hidden="true" tabindex="-1"></a>    std.debug.print(</span>
<span id="cb60-15"><a href="#cb60-15" aria-hidden="true" tabindex="-1"></a>        <span class="st">"Type 4: {}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span><span class="bu">@TypeOf</span>(string_obj)<span class="op">}</span></span>
<span id="cb60-16"><a href="#cb60-16" aria-hidden="true" tabindex="-1"></a>    );</span>
<span id="cb60-17"><a href="#cb60-17" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>Type 1: [4]i32
Type 2: *const [16:0]u8
Type 3: *const [4]i32
Type 4: []const u8</code></pre>
</section>
<section id="byte-vs-unicode-points" class="level3" data-number="1.8.4">
<h3 data-number="1.8.4" class="anchored" data-anchor-id="byte-vs-unicode-points"><span class="header-section-number">1.8.4</span> Byte vs unicode points</h3>
<p>It’s important to point out that each byte in the array is not necessarily a single character. This fact arises from the difference between a single byte and a single unicode point.</p>
<p>The encoding UTF-8 works by assigning a number (which is called a unicode point) to each character in the string. For example, the character “H” is stored in UTF-8 as the decimal number 72. This means that the number 72 is the unicode point for the character “H”. Each possible character that can appear in a UTF-8 encoded string have its own unicode point.</p>
<p>For example, the Latin Capital Letter A With Stroke (Ⱥ) is represented by the number (or the unicode point) 570. However, this decimal number (570) is higher than the maximum number stored inside a single byte, which is 255. In other words, the maximum decimal number that can be represented with a single byte is 255. That is why, the unicode point 570 is actually stored inside the computer’s memory as the bytes <code>C8 BA</code>.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb62"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb62-1"><a href="#cb62-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb62-2"><a href="#cb62-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb62-3"><a href="#cb62-3" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb62-4"><a href="#cb62-4" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb62-5"><a href="#cb62-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb62-6"><a href="#cb62-6" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb62-7"><a href="#cb62-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">const</span> string_object = <span class="st">"Ⱥ"</span>;</span>
<span id="cb62-8"><a href="#cb62-8" aria-hidden="true" tabindex="-1"></a>    _ = <span class="kw">try</span> stdout.write(</span>
<span id="cb62-9"><a href="#cb62-9" aria-hidden="true" tabindex="-1"></a>        <span class="st">"Bytes that represents the string object: "</span></span>
<span id="cb62-10"><a href="#cb62-10" aria-hidden="true" tabindex="-1"></a>    );</span>
<span id="cb62-11"><a href="#cb62-11" aria-hidden="true" tabindex="-1"></a>    <span class="kw">for</span> (string_object) |char| <span class="op">{</span></span>
<span id="cb62-12"><a href="#cb62-12" aria-hidden="true" tabindex="-1"></a>        <span class="kw">try</span> stdout.print(<span class="st">"{X} "</span>, .<span class="op">{</span>char<span class="op">}</span>);</span>
<span id="cb62-13"><a href="#cb62-13" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb62-14"><a href="#cb62-14" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb62-15"><a href="#cb62-15" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Bytes that represents the string object: C8 BA </code></pre>
</div>
</div>
<p>This means that to store the character Ⱥ in a UTF-8 encoded string, we need to use two bytes together to represent the number 570. That is why the relationship between bytes and unicode points is not always 1 to 1. Each unicode point is a single character in the string, but not always a single byte corresponds to a single unicode point.</p>
<p>All of this means that if you loop through the elements of a string in Zig, you will be looping through the bytes that represents that string, and not through the characters of that string. In the Ⱥ example above, the for loop needed two iterations (instead of a single iteration) to print the two bytes that represents this Ⱥ letter.</p>
<p>Now, all english letters (or ASCII letters if you prefer) can be represented by a single byte in UTF-8. As a consequence, if your UTF-8 string contains only english letters (or ASCII letters), then, you are lucky. Because the number of bytes will be equal to the number of characters in that string. In other words, in this specific situation, the relationship between bytes and unicode points is 1 to 1.</p>
<p>But on the other side, if your string contains other types of letters… for example, you might be working with text data that contains, chinese, japanese or latin letters, then, the number of bytes necessary to represent your UTF-8 string will likely be much higher than the number of characters in that string.</p>
<p>If you need to iterate through the characters of a string, instead of its bytes, then, you can use the <code>std.unicode.Utf8View</code> struct to create an iterator that iterates through the unicode points of your string.</p>
<p>In the example below, we loop through the japanese characters “アメリカ”. Each of the four characters in this string is represented by three bytes. But the for loop iterates four times, one iteration for each character/unicode point in this string:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb64"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb64-1"><a href="#cb64-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> std = <span class="bu">@import</span>(<span class="st">"std"</span>);</span>
<span id="cb64-2"><a href="#cb64-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_buffer: [<span class="dv">1024</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb64-3"><a href="#cb64-3" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> stdout_writer = std.fs.File.stdout().writer(&amp;stdout_buffer);</span>
<span id="cb64-4"><a href="#cb64-4" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> stdout = &amp;stdout_writer.interface;</span>
<span id="cb64-5"><a href="#cb64-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb64-6"><a href="#cb64-6" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> main() !<span class="dt">void</span> <span class="op">{</span></span>
<span id="cb64-7"><a href="#cb64-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> utf8 = <span class="kw">try</span> std.unicode.Utf8View.init(<span class="st">"アメリカ"</span>);</span>
<span id="cb64-8"><a href="#cb64-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">var</span> iterator = utf8.iterator();</span>
<span id="cb64-9"><a href="#cb64-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">while</span> (iterator.nextCodepointSlice()) |codepoint| <span class="op">{</span></span>
<span id="cb64-10"><a href="#cb64-10" aria-hidden="true" tabindex="-1"></a>        <span class="kw">try</span> stdout.print(</span>
<span id="cb64-11"><a href="#cb64-11" aria-hidden="true" tabindex="-1"></a>            <span class="st">"got codepoint {x}</span><span class="sc">\n</span><span class="st">"</span>,</span>
<span id="cb64-12"><a href="#cb64-12" aria-hidden="true" tabindex="-1"></a>            .<span class="op">{</span>codepoint<span class="op">}</span>,</span>
<span id="cb64-13"><a href="#cb64-13" aria-hidden="true" tabindex="-1"></a>        );</span>
<span id="cb64-14"><a href="#cb64-14" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb64-15"><a href="#cb64-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb64-16"><a href="#cb64-16" aria-hidden="true" tabindex="-1"></a>    <span class="kw">try</span> stdout.flush();</span>
<span id="cb64-17"><a href="#cb64-17" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>got codepoint e382a2
got codepoint e383a1
got codepoint e383aa
got codepoint e382ab</code></pre>
</section>
<section id="sec-strings-useful-funs" class="level3" data-number="1.8.5">
<h3 data-number="1.8.5" class="anchored" data-anchor-id="sec-strings-useful-funs"><span class="header-section-number">1.8.5</span> Some useful functions for strings</h3>
<p>In this section, I just want to quickly describe some functions from the Zig Standard Library that are very useful to use when working with strings. Most notably:</p>
<ul>
<li><code>std.mem.eql()</code>: to compare if two strings are equal.</li>
<li><code>std.mem.splitScalar()</code>: to split a string into an array of substrings given a delimiter value.</li>
<li><code>std.mem.splitSequence()</code>: to split a string into an array of substrings given a substring delimiter.</li>
<li><code>std.mem.startsWith()</code>: to check if string starts with substring.</li>
<li><code>std.mem.endsWith()</code>: to check if string ends with substring.</li>
<li><code>std.mem.trim()</code>: to remove specific values from both start and end of the string.</li>
<li><code>std.mem.concat()</code>: to concatenate strings together.</li>
<li><code>std.mem.count()</code>: to count the occurrences of substring in the string.</li>
<li><code>std.mem.replace()</code>: to replace the occurrences of substring in the string.</li>
</ul>
<p>Notice that all of these functions come from the <code>mem</code> module of the Zig Standard Library. This module contains multiple functions and methods that are useful to work with memory and sequences of bytes in general.</p>
<p>The <code>eql()</code> function is used to check if two arrays of data are equal or not. Since strings are just arbitrary arrays of bytes, we can use this function to compare two strings together. This function returns a boolean value indicating if the two strings are equal or not. The first argument of this function is the data type of the elements of the arrays that are being compared.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb66"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb66-1"><a href="#cb66-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> name: []<span class="kw">const</span> <span class="dt">u8</span> = <span class="st">"Pedro"</span>;</span>
<span id="cb66-2"><a href="#cb66-2" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(</span>
<span id="cb66-3"><a href="#cb66-3" aria-hidden="true" tabindex="-1"></a>    <span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>std.mem.eql(<span class="dt">u8</span>, name, <span class="st">"Pedro"</span>)<span class="op">}</span></span>
<span id="cb66-4"><a href="#cb66-4" aria-hidden="true" tabindex="-1"></a>);</span>
<span id="cb66-5"><a href="#cb66-5" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>true</code></pre>
</div>
</div>
<p>The <code>splitScalar()</code> and <code>splitSequence()</code> functions are useful to split a string into multiple fragments, like the <code>split()</code> method from Python strings. The difference between these two methods is that the <code>splitScalar()</code> uses a single character as the separator to split the string, while <code>splitSequence()</code> uses a sequence of characters (a.k.a. a substring) as the separator. There is a practical example of these functions later in the book.</p>
<p>The <code>startsWith()</code> and <code>endsWith()</code> functions are pretty straightforward. They return a boolean value indicating if the string (or, more precisely, if the array of data) begins (<code>startsWith</code>) or ends (<code>endsWith</code>) with the sequence provided.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb68"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb68-1"><a href="#cb68-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> name: []<span class="kw">const</span> <span class="dt">u8</span> = <span class="st">"Pedro"</span>;</span>
<span id="cb68-2"><a href="#cb68-2" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(</span>
<span id="cb68-3"><a href="#cb68-3" aria-hidden="true" tabindex="-1"></a>    <span class="st">"{any}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>std.mem.startsWith(<span class="dt">u8</span>, name, <span class="st">"Pe"</span>)<span class="op">}</span></span>
<span id="cb68-4"><a href="#cb68-4" aria-hidden="true" tabindex="-1"></a>);</span>
<span id="cb68-5"><a href="#cb68-5" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>true</code></pre>
</div>
</div>
<p>The <code>concat()</code> function, as the name suggests, concatenate two or more strings together. Because the process of concatenating the strings involves allocating enough space to accomodate all the strings together, this <code>concat()</code> function receives an allocator object as input.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb70"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb70-1"><a href="#cb70-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> str1 = <span class="st">"Hello"</span>;</span>
<span id="cb70-2"><a href="#cb70-2" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> str2 = <span class="st">" you!"</span>;</span>
<span id="cb70-3"><a href="#cb70-3" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> str3 = <span class="kw">try</span> std.mem.concat(</span>
<span id="cb70-4"><a href="#cb70-4" aria-hidden="true" tabindex="-1"></a>    allocator, <span class="dt">u8</span>, &amp;[_][]<span class="kw">const</span> <span class="dt">u8</span><span class="op">{</span> str1, str2 <span class="op">}</span></span>
<span id="cb70-5"><a href="#cb70-5" aria-hidden="true" tabindex="-1"></a>);</span>
<span id="cb70-6"><a href="#cb70-6" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"{s}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>str3<span class="op">}</span>);</span>
<span id="cb70-7"><a href="#cb70-7" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>As you can imagine, the <code>replace()</code> function is used to replace substrings in a string by another substring. This function works very similarly to the <code>replace()</code> method from Python strings. Therefore, you provide a substring to search, and every time that the <code>replace()</code> function finds this substring within the input string, it replaces this substring with the “replacement substring” that you provided as input.</p>
<p>In the example below, we are taking the input string “Hello”, and replacing all occurrences of the substring “el” inside this input string with “34”, and saving the results inside the <code>buffer</code> object. As result, the <code>replace()</code> function returns an <code>usize</code> value that indicates how many replacements were performed.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb71"><pre class="sourceCode zig code-with-copy"><code class="sourceCode zig"><span id="cb71-1"><a href="#cb71-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> str1 = <span class="st">"Hello"</span>;</span>
<span id="cb71-2"><a href="#cb71-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> buffer: [<span class="dv">5</span>]<span class="dt">u8</span> = <span class="cn">undefined</span>;</span>
<span id="cb71-3"><a href="#cb71-3" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> nrep = std.mem.replace(</span>
<span id="cb71-4"><a href="#cb71-4" aria-hidden="true" tabindex="-1"></a>    <span class="dt">u8</span>, str1, <span class="st">"el"</span>, <span class="st">"34"</span>, buffer[<span class="dv">0</span>..]</span>
<span id="cb71-5"><a href="#cb71-5" aria-hidden="true" tabindex="-1"></a>);</span>
<span id="cb71-6"><a href="#cb71-6" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"New string: {s}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>buffer<span class="op">}</span>);</span>
<span id="cb71-7"><a href="#cb71-7" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.print(<span class="st">"N of replacements: {d}</span><span class="sc">\n</span><span class="st">"</span>, .<span class="op">{</span>nrep<span class="op">}</span>);</span>
<span id="cb71-8"><a href="#cb71-8" aria-hidden="true" tabindex="-1"></a><span class="kw">try</span> stdout.flush();</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<pre><code>New string: H34lo
N of replacements: 1</code></pre>
</section>
</section>
<section id="safety-in-zig" class="level2" data-number="1.9">
<h2 data-number="1.9" class="anchored" data-anchor-id="safety-in-zig"><span class="header-section-number">1.9</span> Safety in Zig</h2>
<p>A general trend in modern low-level programming languages is safety. As our modern world becomes more interconnected with technology and computers, the data produced by all of this technology becomes one of the most important (and also, one of the most dangerous) assets that we have.</p>
<p>This is probably the main reason why modern low-level programming languages have been giving great attention to safety, especially memory safety, because memory corruption is still the main target for hackers to exploit. The reality is that we don’t have an easy solution for this problem. For now, we only have techniques and strategies that mitigates these problems.</p>
<p>As Richard Feldman explains on his <a href="https://www.youtube.com/watch?v=jIZpKpLCOiU&amp;ab_channel=GOTOConferences">most recent GOTO conference talk</a><a href="#fn25" class="footnote-ref" id="fnref25" role="doc-noteref"><sup>25</sup></a> , we haven’t figured it out yet a way to achieve <strong>true safety in technology</strong>. In other words, we haven’t found a way to build software that won’t be exploited with 100% certainty. We can greatly reduce the risks of our software being exploited, by ensuring memory safety for example. But this is not enough to achieve “true safety” territory.</p>
<p>Because even if you write your program in a “safe language”, hackers can still exploit failures in the operating system where your program is running (e.g.&nbsp;maybe the system where your code is running has a “backdoor exploit” that can still affect your code in unexpected ways), or also, they can exploit the features from the architecture of your computer. A recently found exploit that involves memory invalidation through a feature of “memory tags” present in ARM chips is an example of that <span class="citation" data-cites="exploit1">(<a href="references.html#ref-exploit1" role="doc-biblioref">Kim et al. 2024</a>)</span>.</p>
<p>The question is: what have Zig and other languages been doing to mitigate this problem? If we take Rust as an example, Rust is, for the most part<a href="#fn26" class="footnote-ref" id="fnref26" role="doc-noteref"><sup>26</sup></a>, a memory safe language by enforcing specific rules to the developer. In other words, the key feature of Rust, the <em>borrow checker</em>, forces you to follow a specific logic when you are writing your Rust code, and the Rust compiler will always complain everytime you try to go out of this pattern.</p>
<p>In contrast, the Zig language is not a memory safe language by default. There are some memory safety features that you get for free in Zig, especially in arrays and pointer objects. But there are other tools offered by the language, that are not used by default. In other words, the <code>zig</code> compiler does not obligate you to use such tools.</p>
<p>The tools listed below are related to memory safety. That is, they help you to achieve memory safety in your Zig code:</p>
<ul>
<li><code>defer</code> allows you to keep free operations physically close to allocations. This helps you to avoid memory leaks, “use after free”, and also “double-free” problems. Furthermore, it also keeps free operations logically tied to the end of the current scope, which greatly reduces the mental overhead about object lifetime.</li>
<li><code>errdefer</code> helps you to guarantee that your program frees the allocated memory, even if a runtime error occurs.</li>
<li>pointers and objects are non-nullable by default. This helps you to avoid memory problems that might arise from de-referencing null pointers.</li>
<li>Zig offers some native types of allocators (called “testing allocators”) that can detect memory leaks and double-frees. These types of allocators are widely used on unit tests, so they transform your unit tests into a weapon that you can use to detect memory problems in your code.</li>
<li>arrays and slices in Zig have their lengths embedded in the object itself, which makes the <code>zig</code> compiler very effective on detecting “index out-of-range” type of errors, and avoiding buffer overflows.</li>
</ul>
<p>Despite these features that Zig offers that are related to memory safety issues, the language also has some rules that help you to achieve another type of safety, which is more related to program logic safety. These rules are:</p>
<ul>
<li>pointers and objects are non-nullable by default. Which eliminates an edge case that might break the logic of your program.</li>
<li>switch statements must exaust all possible options.</li>
<li>the <code>zig</code> compiler forces you to handle every possible error in your program.</li>
</ul>
</section>
<section id="other-parts-of-zig" class="level2" data-number="1.10">
<h2 data-number="1.10" class="anchored" data-anchor-id="other-parts-of-zig"><span class="header-section-number">1.10</span> Other parts of Zig</h2>
<p>We already learned a lot about Zig’s syntax, and also, some pretty technical details about it. Just as a quick recap:</p>
<ul>
<li>We talked about how functions are written in Zig in <a href="#sec-root-file" class="quarto-xref"><span>Section 1.2.2</span></a> and <a href="#sec-main-file" class="quarto-xref"><span>Section 1.2.3</span></a>.</li>
<li>How to create new objects/identifiers in <a href="#sec-root-file" class="quarto-xref"><span>Section 1.2.2</span></a> and especially in <a href="#sec-assignments" class="quarto-xref"><span>Section 1.4</span></a>.</li>
<li>How strings work in Zig in <a href="#sec-zig-strings" class="quarto-xref"><span>Section 1.8</span></a>.</li>
<li>How to use arrays and slices in <a href="#sec-arrays" class="quarto-xref"><span>Section 1.6</span></a>.</li>
<li>How to import functionality from other Zig modules in <a href="#sec-root-file" class="quarto-xref"><span>Section 1.2.2</span></a>.</li>
</ul>
<p>But, for now, this amount of knowledge is enough for us to continue with this book. Later, over the next chapters we will still talk more about other parts of Zig’s syntax that are also equally important. Such as:</p>
<ul>
<li>How Object-Oriented programming can be done in Zig through <em>struct declarations</em> in <a href="03-structs.html#sec-structs-and-oop" class="quarto-xref"><span>Section 2.3</span></a>.</li>
<li>Basic control flow syntax in <a href="03-structs.html#sec-zig-control-flow" class="quarto-xref"><span>Section 2.1</span></a>.</li>
<li>Enums in <a href="04-http-server.html#sec-enum" class="quarto-xref"><span>Section 7.6</span></a>;</li>
<li>Pointers and Optionals in <a href="05-pointers.html" class="quarto-xref"><span>Chapter 6</span></a>;</li>
<li>Error handling with <code>try</code> and <code>catch</code> in <a href="09-error-handling.html" class="quarto-xref"><span>Chapter 10</span></a>;</li>
<li>Unit tests in <a href="03-unittests.html" class="quarto-xref"><span>Chapter 8</span></a>;</li>
<li>Vectors in <a href="15-vectors.html" class="quarto-xref"><span>Chapter 17</span></a>;</li>
<li>Build System in <a href="07-build-system.html" class="quarto-xref"><span>Chapter 9</span></a>;</li>
</ul>


<div id="refs" class="references csl-bib-body hanging-indent" data-entry-spacing="0" role="list" style="display: none">
<div id="ref-exploit1" class="csl-entry" role="listitem">
Kim, Juhee, Jinbum Park, Sihyeon Roh, Jaeyoung Chung, Youngjoo Lee, Taesoo Kim, and Byoungyoung Lee. 2024. <span>“TikTag: Breaking ARM’s Memory Tagging Extension with Speculative Execution.”</span> <a href="https://arxiv.org/abs/2406.08719">https://arxiv.org/abs/2406.08719</a>.
</div>
<div id="ref-zigguide" class="csl-entry" role="listitem">
Sobeston. 2024. <span>“Zig Guide.”</span> <a href="https://zig.guide/">https://zig.guide/</a>.
</div>
</div>
</section>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr>
<ol>
<li id="fn1"><p><a href="https://ziglang.org/learn/overview/#zig-build-system" class="uri">https://ziglang.org/learn/overview/#zig-build-system</a>.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p><a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e" class="uri">https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e</a><a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn3"><p><a href="https://medium.com/@edlyuu/zig-package-manager-2-wtf-is-build-zig-zon-and-build-zig-0-11-0-update-5bc46e830fc1" class="uri">https://medium.com/@edlyuu/zig-package-manager-2-wtf-is-build-zig-zon-and-build-zig-0-11-0-update-5bc46e830fc1</a><a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn4"><p><a href="https://github.com/ziglang/zig/blob/master/doc/build.zig.zon.md" class="uri">https://github.com/ziglang/zig/blob/master/doc/build.zig.zon.md</a><a href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn5"><p><a href="https://en.wikipedia.org/wiki/List_of_C-family_programming_languages" class="uri">https://en.wikipedia.org/wiki/List_of_C-family_programming_languages</a><a href="#fnref5" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn6"><p>You can see an example of a <code>main()</code> function that returns a <code>u8</code> value in the <code>return-integer.zig</code> file, <a href="https://github.com/pedropark99/zig-book/blob/main/ZigExamples/zig-basics/return-integer.zig" class="uri">https://github.com/pedropark99/zig-book/blob/main/ZigExamples/zig-basics/return-integer.zig</a><a href="#fnref6" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn7"><p><a href="https://github.com/ziglang/zig/issues/17186" class="uri">https://github.com/ziglang/zig/issues/17186</a><a href="#fnref7" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn8"><p><a href="https://github.com/ziglang/zig/issues/19864" class="uri">https://github.com/ziglang/zig/issues/19864</a><a href="#fnref8" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn9"><p><a href="https://github.com/ziglang/zig/tree/master/lib/std" class="uri">https://github.com/ziglang/zig/tree/master/lib/std</a><a href="#fnref9" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn10"><p><a href="https://github.com/oven-sh/bun" class="uri">https://github.com/oven-sh/bun</a>.<a href="#fnref10" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn11"><p><a href="https://github.com/hexops/mach" class="uri">https://github.com/hexops/mach</a><a href="#fnref11" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn12"><p><a href="https://github.com/cgbur/llama2.zig/tree/main" class="uri">https://github.com/cgbur/llama2.zig/tree/main</a><a href="#fnref12" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn13"><p><a href="https://github.com/tigerbeetle/tigerbeetle" class="uri">https://github.com/tigerbeetle/tigerbeetle</a><a href="#fnref13" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn14"><p><a href="https://github.com/Hejsil/zig-clap" class="uri">https://github.com/Hejsil/zig-clap</a><a href="#fnref14" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn15"><p><a href="https://github.com/capy-ui/capy" class="uri">https://github.com/capy-ui/capy</a><a href="#fnref15" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn16"><p><a href="https://github.com/zigtools/zls" class="uri">https://github.com/zigtools/zls</a><a href="#fnref16" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn17"><p><a href="https://github.com/mitchellh/libxev" class="uri">https://github.com/mitchellh/libxev</a><a href="#fnref17" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn18"><p><a href="https://ziglings.org" class="uri">https://ziglings.org</a>.<a href="#fnref18" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn19"><p><a href="https://www.youtube.com/watch?v=OPuztQfM3Fg&amp;t=2524s&amp;ab_channel=TheVimeagen" class="uri">https://www.youtube.com/watch?v=OPuztQfM3Fg&amp;t=2524s&amp;ab_channel=TheVimeagen</a>.<a href="#fnref19" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn20"><p><a href="https://adventofcode.com/" class="uri">https://adventofcode.com/</a><a href="#fnref20" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn21"><p><a href="https://ziglang.org/documentation/master/#Primitive-Types" class="uri">https://ziglang.org/documentation/master/#Primitive-Types</a>.<a href="#fnref21" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn22"><p><a href="https://www.gnu.org/software/libiconv/" class="uri">https://www.gnu.org/software/libiconv/</a><a href="#fnref22" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn23"><p><a href="https://ziglang.org/documentation/master/#Sentinel-Terminated-Arrays" class="uri">https://ziglang.org/documentation/master/#Sentinel-Terminated-Arrays</a>.<a href="#fnref23" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn24"><p><a href="https://cplusplus.com/reference/cstdio/printf/" class="uri">https://cplusplus.com/reference/cstdio/printf/</a><a href="#fnref24" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn25"><p><a href="https://www.youtube.com/watch?v=jIZpKpLCOiU&amp;ab_channel=GOTOConferences" class="uri">https://www.youtube.com/watch?v=jIZpKpLCOiU&amp;ab_channel=GOTOConferences</a><a href="#fnref25" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn26"><p>Actually, a lot of existing Rust code is still memory unsafe, because they communicate with external libraries through FFI (<em>foreign function interface</em>), which disables the borrow-checker features through the <code>unsafe</code> keyword.<a href="#fnref26" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>

</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
  window.document.addEventListener("DOMContentLoaded", function (event) {
    // Ensure there is a toggle, if there isn't float one in the top right
    if (window.document.querySelector('.quarto-color-scheme-toggle') === null) {
      const a = window.document.createElement('a');
      a.classList.add('top-right');
      a.classList.add('quarto-color-scheme-toggle');
      a.href = "";
      a.onclick = function() { try { window.quartoToggleColorScheme(); } catch {} return false; };
      const i = window.document.createElement("i");
      i.classList.add('bi');
      a.appendChild(i);
      window.document.body.appendChild(a);
    }
    setColorSchemeToggle(hasAlternateSentinel())
    const icon = "";
    const anchorJS = new window.AnchorJS();
    anchorJS.options = {
      placement: 'right',
      icon: icon
    };
    anchorJS.add('.anchored');
    const isCodeAnnotation = (el) => {
      for (const clz of el.classList) {
        if (clz.startsWith('code-annotation-')) {                     
          return true;
        }
      }
      return false;
    }
    const onCopySuccess = function(e) {
      // button target
      const button = e.trigger;
      // don't keep focus
      button.blur();
      // flash "checked"
      button.classList.add('code-copy-button-checked');
      var currentTitle = button.getAttribute("title");
      button.setAttribute("title", "Copied!");
      let tooltip;
      if (window.bootstrap) {
        button.setAttribute("data-bs-toggle", "tooltip");
        button.setAttribute("data-bs-placement", "left");
        button.setAttribute("data-bs-title", "Copied!");
        tooltip = new bootstrap.Tooltip(button, 
          { trigger: "manual", 
            customClass: "code-copy-button-tooltip",
            offset: [0, -8]});
        tooltip.show();    
      }
      setTimeout(function() {
        if (tooltip) {
          tooltip.hide();
          button.removeAttribute("data-bs-title");
          button.removeAttribute("data-bs-toggle");
          button.removeAttribute("data-bs-placement");
        }
        button.setAttribute("title", currentTitle);
        button.classList.remove('code-copy-button-checked');
      }, 1000);
      // clear code selection
      e.clearSelection();
    }
    const getTextToCopy = function(trigger) {
        const codeEl = trigger.previousElementSibling.cloneNode(true);
        for (const childEl of codeEl.children) {
          if (isCodeAnnotation(childEl)) {
            childEl.remove();
          }
        }
        return codeEl.innerText;
    }
    const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
      text: getTextToCopy
    });
    clipboard.on('success', onCopySuccess);
    if (window.document.getElementById('quarto-embedded-source-code-modal')) {
      const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
        text: getTextToCopy,
        container: window.document.getElementById('quarto-embedded-source-code-modal')
      });
      clipboardModal.on('success', onCopySuccess);
    }
      var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
      var mailtoRegex = new RegExp(/^mailto:/);
        var filterRegex = new RegExp('/' + window.location.host + '/');
      var isInternal = (href) => {
          return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
      }
      // Inspect non-navigation links and adorn them if external
     var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
      for (var i=0; i<links.length; i++) {
        const link = links[i];
        if (!isInternal(link.href)) {
          // undo the damage that might have been done by quarto-nav.js in the case of
          // links that we want to consider external
          if (link.dataset.originalHref !== undefined) {
            link.href = link.dataset.originalHref;
          }
        }
      }
    function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
      const config = {
        allowHTML: true,
        maxWidth: 500,
        delay: 100,
        arrow: false,
        appendTo: function(el) {
            return el.parentElement;
        },
        interactive: true,
        interactiveBorder: 10,
        theme: 'quarto',
        placement: 'bottom-start',
      };
      if (contentFn) {
        config.content = contentFn;
      }
      if (onTriggerFn) {
        config.onTrigger = onTriggerFn;
      }
      if (onUntriggerFn) {
        config.onUntrigger = onUntriggerFn;
      }
      window.tippy(el, config); 
    }
    const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
    for (var i=0; i<noterefs.length; i++) {
      const ref = noterefs[i];
      tippyHover(ref, function() {
        // use id or data attribute instead here
        let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
        try { href = new URL(href).hash; } catch {}
        const id = href.replace(/^#\/?/, "");
        const note = window.document.getElementById(id);
        if (note) {
          return note.innerHTML;
        } else {
          return "";
        }
      });
    }
    const xrefs = window.document.querySelectorAll('a.quarto-xref');
    const processXRef = (id, note) => {
      // Strip column container classes
      const stripColumnClz = (el) => {
        el.classList.remove("page-full", "page-columns");
        if (el.children) {
          for (const child of el.children) {
            stripColumnClz(child);
          }
        }
      }
      stripColumnClz(note)
      if (id === null || id.startsWith('sec-')) {
        // Special case sections, only their first couple elements
        const container = document.createElement("div");
        if (note.children && note.children.length > 2) {
          container.appendChild(note.children[0].cloneNode(true));
          for (let i = 1; i < note.children.length; i++) {
            const child = note.children[i];
            if (child.tagName === "P" && child.innerText === "") {
              continue;
            } else {
              container.appendChild(child.cloneNode(true));
              break;
            }
          }
          if (window.Quarto?.typesetMath) {
            window.Quarto.typesetMath(container);
          }
          return container.innerHTML
        } else {
          if (window.Quarto?.typesetMath) {
            window.Quarto.typesetMath(note);
          }
          return note.innerHTML;
        }
      } else {
        // Remove any anchor links if they are present
        const anchorLink = note.querySelector('a.anchorjs-link');
        if (anchorLink) {
          anchorLink.remove();
        }
        if (window.Quarto?.typesetMath) {
          window.Quarto.typesetMath(note);
        }
        if (note.classList.contains("callout")) {
          return note.outerHTML;
        } else {
          return note.innerHTML;
        }
      }
    }
    for (var i=0; i<xrefs.length; i++) {
      const xref = xrefs[i];
      tippyHover(xref, undefined, function(instance) {
        instance.disable();
        let url = xref.getAttribute('href');
        let hash = undefined; 
        if (url.startsWith('#')) {
          hash = url;
        } else {
          try { hash = new URL(url).hash; } catch {}
        }
        if (hash) {
          const id = hash.replace(/^#\/?/, "");
          const note = window.document.getElementById(id);
          if (note !== null) {
            try {
              const html = processXRef(id, note.cloneNode(true));
              instance.setContent(html);
            } finally {
              instance.enable();
              instance.show();
            }
          } else {
            // See if we can fetch this
            fetch(url.split('#')[0])
            .then(res => res.text())
            .then(html => {
              const parser = new DOMParser();
              const htmlDoc = parser.parseFromString(html, "text/html");
              const note = htmlDoc.getElementById(id);
              if (note !== null) {
                const html = processXRef(id, note);
                instance.setContent(html);
              } 
            }).finally(() => {
              instance.enable();
              instance.show();
            });
          }
        } else {
          // See if we can fetch a full url (with no hash to target)
          // This is a special case and we should probably do some content thinning / targeting
          fetch(url)
          .then(res => res.text())
          .then(html => {
            const parser = new DOMParser();
            const htmlDoc = parser.parseFromString(html, "text/html");
            const note = htmlDoc.querySelector('main.content');
            if (note !== null) {
              // This should only happen for chapter cross references
              // (since there is no id in the URL)
              // remove the first header
              if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
                note.children[0].remove();
              }
              const html = processXRef(null, note);
              instance.setContent(html);
            } 
          }).finally(() => {
            instance.enable();
            instance.show();
          });
        }
      }, function(instance) {
      });
    }
        let selectedAnnoteEl;
        const selectorForAnnotation = ( cell, annotation) => {
          let cellAttr = 'data-code-cell="' + cell + '"';
          let lineAttr = 'data-code-annotation="' +  annotation + '"';
          const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
          return selector;
        }
        const selectCodeLines = (annoteEl) => {
          const doc = window.document;
          const targetCell = annoteEl.getAttribute("data-target-cell");
          const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
          const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
          const lines = annoteSpan.getAttribute("data-code-lines").split(",");
          const lineIds = lines.map((line) => {
            return targetCell + "-" + line;
          })
          let top = null;
          let height = null;
          let parent = null;
          if (lineIds.length > 0) {
              //compute the position of the single el (top and bottom and make a div)
              const el = window.document.getElementById(lineIds[0]);
              top = el.offsetTop;
              height = el.offsetHeight;
              parent = el.parentElement.parentElement;
            if (lineIds.length > 1) {
              const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
              const bottom = lastEl.offsetTop + lastEl.offsetHeight;
              height = bottom - top;
            }
            if (top !== null && height !== null && parent !== null) {
              // cook up a div (if necessary) and position it 
              let div = window.document.getElementById("code-annotation-line-highlight");
              if (div === null) {
                div = window.document.createElement("div");
                div.setAttribute("id", "code-annotation-line-highlight");
                div.style.position = 'absolute';
                parent.appendChild(div);
              }
              div.style.top = top - 2 + "px";
              div.style.height = height + 4 + "px";
              div.style.left = 0;
              let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
              if (gutterDiv === null) {
                gutterDiv = window.document.createElement("div");
                gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
                gutterDiv.style.position = 'absolute';
                const codeCell = window.document.getElementById(targetCell);
                const gutter = codeCell.querySelector('.code-annotation-gutter');
                gutter.appendChild(gutterDiv);
              }
              gutterDiv.style.top = top - 2 + "px";
              gutterDiv.style.height = height + 4 + "px";
            }
            selectedAnnoteEl = annoteEl;
          }
        };
        const unselectCodeLines = () => {
          const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
          elementsIds.forEach((elId) => {
            const div = window.document.getElementById(elId);
            if (div) {
              div.remove();
            }
          });
          selectedAnnoteEl = undefined;
        };
          // Handle positioning of the toggle
      window.addEventListener(
        "resize",
        throttle(() => {
          elRect = undefined;
          if (selectedAnnoteEl) {
            selectCodeLines(selectedAnnoteEl);
          }
        }, 10)
      );
      function throttle(fn, ms) {
      let throttle = false;
      let timer;
        return (...args) => {
          if(!throttle) { // first call gets through
              fn.apply(this, args);
              throttle = true;
          } else { // all the others get throttled
              if(timer) clearTimeout(timer); // cancel #2
              timer = setTimeout(() => {
                fn.apply(this, args);
                timer = throttle = false;
              }, ms);
          }
        };
      }
        // Attach click handler to the DT
        const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
        for (const annoteDlNode of annoteDls) {
          annoteDlNode.addEventListener('click', (event) => {
            const clickedEl = event.target;
            if (clickedEl !== selectedAnnoteEl) {
              unselectCodeLines();
              const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
              if (activeEl) {
                activeEl.classList.remove('code-annotation-active');
              }
              selectCodeLines(clickedEl);
              clickedEl.classList.add('code-annotation-active');
            } else {
              // Unselect the line
              unselectCodeLines();
              clickedEl.classList.remove('code-annotation-active');
            }
          });
        }
    const findCites = (el) => {
      const parentEl = el.parentElement;
      if (parentEl) {
        const cites = parentEl.dataset.cites;
        if (cites) {
          return {
            el,
            cites: cites.split(' ')
          };
        } else {
          return findCites(el.parentElement)
        }
      } else {
        return undefined;
      }
    };
    var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
    for (var i=0; i<bibliorefs.length; i++) {
      const ref = bibliorefs[i];
      const citeInfo = findCites(ref);
      if (citeInfo) {
        tippyHover(citeInfo.el, function() {
          var popup = window.document.createElement('div');
          citeInfo.cites.forEach(function(cite) {
            var citeDiv = window.document.createElement('div');
            citeDiv.classList.add('hanging-indent');
            citeDiv.classList.add('csl-entry');
            var biblioDiv = window.document.getElementById('ref-' + cite);
            if (biblioDiv) {
              citeDiv.innerHTML = biblioDiv.innerHTML;
            }
            popup.appendChild(citeDiv);
          });
          return popup.innerHTML;
        });
      }
    }
  });
  </script>
<nav class="page-navigation">
  <div class="nav-page nav-page-previous">
      <a href="../index.html" class="pagination-link" aria-label="Welcome">
        <i class="bi bi-arrow-left-short"></i> <span class="nav-page-text">Welcome</span>
      </a>          
  </div>
  <div class="nav-page nav-page-next">
      <a href="../Chapters/03-structs.html" class="pagination-link" aria-label="Control flow, structs, modules and types">
        <span class="nav-page-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Control flow, structs, modules and types</span></span> <i class="bi bi-arrow-right-short"></i>
      </a>
  </div>
</nav>
</div> <!-- /content -->




</body></html>